1

I have a field for a ZIP Code. I want that, when the person fills this field with a zip code and click in another field, triggers a event (onBlur). This Event will execute a select in database and get the address and fill the other fields with this information. I read that is not a good idea execute a Controller Method from the View. So, how can I develop this?

My zip code field:

<div class="editor-field">
    @Html.Label("ZIP CODE")
    @Html.Editor("zipCodeClient")
</div>

Thanks!

2
  • 1
    You need to use Javascript and AJAX. Commented Aug 1, 2012 at 14:29
  • Take a look to: knockoutjs and knockout MVC Commented Aug 1, 2012 at 14:35

1 Answer 1

1

If you have access to jQuery I would use it's ajax function to call a wcf web service that returns the relevant address information in a JSON format. Otherwise, you could create your own XHR request and parse the response.

$('#zipCodeClient').blur(function() {
    var zipCode = $(this).val();
    if(zipCode.length >= 5 && zipCode.length <= 10) {
        $.ajax({
            type: 'GET',
            data: { ZipCode: zipCode },
            url: 'something/ZipCodeToAddressService',
            dataType: 'json',
            contentType:  'application/json; charset=utf-8',
            success: function(data) {
               var responseObject = jQuery.parseJSON(data);
               $('#cityTextBox').val(responseObject.City);
               $('#stateTextBox').val(responseObject.State);
            }
        });
    }
    else {
        // zip code not valid
    }
});

In WCF:

[ServiceContract()]
public interface IAddressServices
{
    [OperationContract()]
    [WebGet(ResponseFormat = WebMessageFormat.Json)]
    string ZipCodeToAddressService(string ZipCode);
}

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class AddressServices : IAddressServices
{
    public string ZipCodeToAddressService(string ZipCode)
    {
        using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
        {
            using (SqlCommand sqlCmd = new SqlCommand("ZipCodeToAddressStoredProc", sqlConnection))
            {
                sqlCmd.CommandType = CommandType.StoredProcedure;
                sqlCmd.Parameters.Add("@Zip", SqlDbType.NVarChar).Value = ZipCode;
                sqlConnection.Open();
                SqlDataReader sDR = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
                DataTable tbl = new DataTable();
                tbl.Load(sDR);
                sDR.Close();
                var citystateData = from DataRow Row in tbl.AsEnumerable()
                                   select new
                                   {
                                      City = Row.Field<string>("City"),
                                      State = Row.Field<string>("State")
                                   };
                JavaScriptSerializer js = new JavaScriptSerializer();
                StringBuilder sb = new StringBuilder();
                js.Serialize(cityStateData, sb);
                string rtrnCityStateData = sb.ToString();
                return rtrnCityStateData;
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Hi! Thanks for your answear. I used this function like you did, but just showing a alert on onBlur, and didn't showed up :( $('#zipCodeClient').onBlur(function () { var zipCode = $(this).val(); alert("OnBlur!"); });
.Net has a weird way of assigning id's to html controls. When you're in debug mode, open the page source in the browser and see what the assigned id is of the text box you're trying to grab the onBlur event on. It will probably be something weird like $ctl00_zipCodeClient - fun.
<input class="text-box single-line" id="zipCodeClient" name="zipCodeClient" type="text" value="" />
Ahhh, in jQuery the event is just .blur not .onBlur. You could also use .focusout

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.