使用JSon对象将数据从Controller传递到View

时间:2011-03-04 20:48:19

标签: asp.net-mvc

我有以下内容从控制器传递Json abject并填充视图中的各种文本框。但是,即使控制器传递有效的Json对象,也不会发生任何事情。这段代码有什么问题???

<script language="javascript" type="text/javascript">

 $(document).ready(function() {
     var url = '<%=Url.Action("DropDownChange") %>';
     $("#vendorID").change(function() {
         var selectedID = $(this).val();
         if (selectedID != "New Vendor Id") {
             //$.post('Url.Action("DropDownChange","Refunds")', function(result) {
             $.post(url, { dropdownValue: selectedID }, function(result) {
                 alert(selectedID);
                 $("#name").val(result.Name);
                 $("#city").val(result.City);
                 $("#contact").val(result.Contact);
                 $("#address2").val(result.Address2);
                 $("#address1").val(result.Address1);
                 $("#state").val(result.State);
                 $("#zip").val(result.Zip);

             });

         }
     });

 });

这是我控制器中的代码;

public JsonResult DropDownChange(string dropdownValue)
    // This action method gets called via an ajax request   
    {


        if (dropdownValue != null && Request.IsAjaxRequest() == true)
        {

            paymentApplicationRefund  =
            cPaymentRepository.PayableEntity(dropdownValue);

            paymentApplicationRefund.Address1.Trim();
            paymentApplicationRefund.Address2.Trim();
            paymentApplicationRefund.Name.Trim();
            paymentApplicationRefund.City.Trim();
            paymentApplicationRefund.Contact.Trim();
            paymentApplicationRefund.State.Trim();
            paymentApplicationRefund.Zip.Trim();

            return Json(paymentApplicationRefund,"application/json");               
        }

        else
        {
            return null;
        }
    }

3 个答案:

答案 0 :(得分:0)

您可能只需要告诉它期待JSON数据。默认情况下,它假定它是HTML。

$.post(url, { dropdownValue: selectedID }, function(result) {
              alert(selectedID);
              $("#name").val(result.Name);
              $("#city").val(result.City);
              $("#contact").val(result.Contact);
              $("#address2").val(result.Address2);
              $("#address1").val(result.Address1);
              $("#state").val(result.State);
              $("#zip").val(result.Zip);
           }, 'json'); 

答案 1 :(得分:0)

我更喜欢以我的DTO作为参数将Json发送到ActionResult,并使用JsonValueProviderFactory对我进行反序列化。

Sending JSON to an ASP.NET MVC Action Method Argument

答案 2 :(得分:0)

试试这个...... 在函数末尾添加“.change()”。

$(document).ready(function() {      
   var url = '<%=Url.Action("DropDownChange") %>';
   $("#vendorID").change(function() {          
   .....
   }).change();
});