您的位置:首页 > 移动开发 > Objective-C

Passing a list of objects from view to controller via jquery ajax(Json(aspx) -> object(C#))

2010-09-28 21:26 881 查看
I have a form that I don't want to post back so I need to get the form values into my controller via jquery's ajax method.

Here is my test controller method:

view plaincopy to clipboardprint?

public ActionResult SavePayment(List<PaymentPostingChargeEntry> lineItems)<BR>{<BR>    return Content("");<BR>}<BR>  

public ActionResult SavePayment(List<PaymentPostingChargeEntry> lineItems)
{
return Content("");
}

Here is my jquery call that I am testing the format of:

 

view plaincopy to clipboardprint?

$.ajax({<BR>    type: "GET",<BR>    url: '/DataEntry/PaymentPosting/SavePayment',<BR>    data: { lineItems: lineItems },<BR>    dataType: "html",<BR>    success: function(result) {<BR>        $("#PaymentMain").html(result);<BR>    },<BR>    error: function(error) {<BR>        alert(error);<BR>    }<BR>});<BR>  

$.ajax({
type: "GET",
url: '/DataEntry/PaymentPosting/SavePayment',
data: { lineItems: lineItems },
dataType: "html",
success: function(result) {
$("#PaymentMain").html(result);
},
error: function(error) {
alert(error);
}
});


The javascript lineItems parameter looks like this:

 

view plaincopy to clipboardprint?

lineItems = { "lineItems[0].Approved": "1.0", "lineItems[0].Deductible": "1.0", "lineItems[0].Coinsurance": "1.0", "lineItems[0].PaymentAmount": "1.0", "lineItems[0].VisitId": "1.0", "lineItems[0].VisitChargeId": "1.0" };  

lineItems = { "lineItems[0].Approved": "1.0", "lineItems[0].Deductible": "1.0", "lineItems[0].Coinsurance": "1.0", "lineItems[0].PaymentAmount": "1.0", "lineItems[0].VisitId": "1.0", "lineItems[0].VisitChargeId": "1.0" };


And finally here is the Object definition for PaymentPostingChargeEntry:

 

view plaincopy to clipboardprint?

public class PaymentPostingChargeEntry<BR>{<BR>    public string Approved { get; set; }<BR>    public string Deductible { get; set; }<BR>    public string Coinsurance { get; set; }<BR>    public string PaymentAmount { get; set; }<BR>    public string VisitId { get; set; }<BR>    public string VisitChargeId { get; set; }<BR>}<BR>  

public class PaymentPostingChargeEntry
{
public string Approved { get; set; }
public string Deductible { get; set; }
public string Coinsurance { get; set; }
public string PaymentAmount { get; set; }
public string VisitId { get; set; }
public string VisitChargeId { get; set; }
}


When I debug the controller method and look at the lineItems parameter, it always contains 0 items. I've tried various formats for the javascipt lineItems parameter but still 0 items. I'm also open to some other way of getting these values in like the jquery form serialze method or something else.
 

Any help would be appreciated.

 

    public class PaymentPostingChargeEntry
    {
        public string Identifier { get; set; }
        public string ChargeAmount { get; set; }
        public string Balance { get; set; }
        public string Approved { get; set; }
        public string Deductible { get; set; }
        public string Coinsurance { get; set; }
        public string PaymentAmount { get; set; }
        public string VisitId { get; set; }
        public string VisitChargeId { get; set; }
    }

Re: Passing a list of objects from view to controller via jquery ajax

01-22-2010, 8:53 PM Contact
Answer
Reply




1,660 point Participant

tpeczek

Member since 01-07-2010, 7:59 AM

Cracow, Poland

Posts 214

Well it took some work, but I think I have a working sample for you :). First javascript function:

view plaincopy to clipboardprint?

<script src="<%= Url.Content("~/Scripts/jquery-1.3.2.min.js") %>" type="text/javascript"></script>  

<script src="<%= Url.Content("~/Scripts/jquery.json-2.2.min.js") %>" type="text/javascript"></script>  

<script type="text/javascript">  

  function savePayment() {   

    //Creating some test data   

    var lineItems = new Object();   

    lineItems.Entrys = new Array();   

    lineItems.Entrys[0] = new Object({ Approved: "1.0", Deductible: "1.0", Coinsurance: "1.0", PaymentAmount: "1.0", VisitId: "1.0", VisitChargeId: "1.0" });   

    lineItems.Entrys[1] = new Object({ Approved: "2.0", Deductible: "2.0", Coinsurance: "2.0", PaymentAmount: "2.0", VisitId: "2.0", VisitChargeId: "2.0" });               

  

    //Posting them to server with ajax   

    $.ajax({   

      type: 'POST',   

      contentType: 'application/json; charset=utf-8',   

      url: '<%=Url.Action("SavePayment", "Home") %>',   

      dataType: 'json',   

      data: $.toJSON(lineItems),   

      success: function(result) {   

        if (result) {   

          alert('Success');   

        }   

        else {   

          alert('Failure');   

        }   

      }   

    });   

  }   

</script>  

<script src="<%= Url.Content("~/Scripts/jquery-1.3.2.min.js") %>" type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/jquery.json-2.2.min.js") %>" type="text/javascript"></script>
<script type="text/javascript">
function savePayment() {
//Creating some test data
var lineItems = new Object();
lineItems.Entrys = new Array();
lineItems.Entrys[0] = new Object({ Approved: "1.0", Deductible: "1.0", Coinsurance: "1.0", PaymentAmount: "1.0", VisitId: "1.0", VisitChargeId: "1.0" });
lineItems.Entrys[1] = new Object({ Approved: "2.0", Deductible: "2.0", Coinsurance: "2.0", PaymentAmount: "2.0", VisitId: "2.0", VisitChargeId: "2.0" });

//Posting them to server with ajax
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '<%=Url.Action("SavePayment", "Home") %>',
dataType: 'json',
data: $.toJSON(lineItems),
success: function(result) {
if (result) {
alert('Success');
}
else {
alert('Failure');
}
}
});
}
</script>

With this code we are posting a javascript object (lineItems), which contains an Array (Entrys) to the server. We are doing this in JSON format (this script requires jQuery and jQuery JSON plugin, which you can download from here: http://code.google.com/p/jquery-json/). ASP.NET MVC can't bind JSON by default, so we need to write JSON model binder:

view plaincopy to clipboardprint?

/// <summary>   

/// Model binder which allows binding JSON data to objects   

/// </summary>   

public class JsonModelBinder : IModelBinder   

{  

  #region IModelBinder Members   

  public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)   

  {   

    if (controllerContext == null)   

      throw new ArgumentNullException("controllerContext");   

    if (bindingContext == null)   

      throw new ArgumentNullException("bindingContext");   

  

    var serializer = new DataContractJsonSerializer(bindingContext.ModelType);   

    return serializer.ReadObject(controllerContext.HttpContext.Request.InputStream);   

  }  

  #endregion   

}  

/// <summary>
/// Model binder which allows binding JSON data to objects
/// </summary>
public class JsonModelBinder : IModelBinder
{
#region IModelBinder Members
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (controllerContext == null)
throw new ArgumentNullException("controllerContext");
if (bindingContext == null)
throw new ArgumentNullException("bindingContext");

var serializer = new DataContractJsonSerializer(bindingContext.ModelType);
return serializer.ReadObject(controllerContext.HttpContext.Request.InputStream);
}
#endregion
}

Now we need to prepare container for list:

view plaincopy to clipboardprint?

[DataContract]   

[ModelBinder(typeof(JsonModelBinder))]   

public class PaymentPostingChargeEntrys   

{   

  [DataMember]   

  public List<PaymentPostingChargeEntry> Entrys { get; set; }   

}  

[DataContract]
[ModelBinder(typeof(JsonModelBinder))]
public class PaymentPostingChargeEntrys
{
[DataMember]
public List<PaymentPostingChargeEntry> Entrys { get; set; }
}

And the last thing to do is controller action:

view plaincopy to clipboardprint?

[AcceptVerbs(HttpVerbs.Post)]   

public ActionResult SavePayment(PaymentPostingChargeEntrys lineItems)   

{   

  return Json(true);   

}  

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SavePayment(PaymentPostingChargeEntrys lineItems)
{
return Json(true);
}

That should give you what you want (of course after some modifications). I hope it will help you.

 

In case I have misunderstood you, and went to far with my sample, here is my blog post with simple ajax form in ASP.NET MVC:

http://tpeczek.blogspot.com/2010/01/asynchronous-form-in-aspnet-mvc.html

Please indicate "Mark as Answer" if a post has answered the question.
Yet another developer blog <-- visit my blog

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery json object ajax list c#
相关文章推荐