1

我有一个邮政编码字段。我希望,当此人用邮政编码填写此字段并单击另一个字段时,会触发一个事件(onBlur)。此事件将在数据库中执行选择并获取地址并使用此信息填充其他字段。我读到从视图中执行控制器方法不是一个好主意。那么,我该如何开发呢?

我的邮政编码字段:

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

谢谢!

4

1 回答 1

1

如果您可以访问 jQuery,我会使用它的 ajax 函数来调用 wcf Web 服务,该服务以 JSON 格式返回相关地址信息。否则,您可以创建自己的 XHR 请求并解析响应。

$('#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
    }
});

在 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;
            }
        }
    }
}
于 2012-08-01T14:42:12.300 回答