How to use model binding with jquery

2019-09-04 21:28发布

问题:

The MVC model binder is doing a great job of picking up values from my page and passing them into my action methods as properties in my complex input.

I'm trying to create a shopping cart type of page, where the user can configure a list of line items, then submit the entire order.

At first I was using Ajax forms for when the user wanted to add an item -- the list of existing lineitems would be passed back to the controller, a new lineitem would be added, and a partial view for the list returned.

Unfortunately, looks like you can't redirect to another page after an Ajax form is submitted. I don't want to do it in jQuery though, because I don't want to deal with explicitly creating the list of complex objects when the MVC model binder does such a good job of it.

EDIT: To clarify, here is my problem:

I want my form to have 2 operations, both of these require the list of lineitems to be passed back.

It is my understanding that I have to do at least one of these operations using javascript. Either:

  1. Use an HtmlForm to submit the entire order, return a new view
  2. Add the lineitem with jQuery when the "add item" button is clicked

OR

  1. Use an AjaxForm to dynamically add new lineitems
  2. Use javascript to do the redirect after the order is submitted, but this means I have to submit the data using javascript as well

Is there a way I can do this without using javascript? I don't want to create the list of lineitems myself with JSON when the movdel binder does it without any work on my part.

回答1:

Ok, I think understand what you need...

  • get the target action url from the form action attribute
  • serialize the form to send it to the controller

and redirect to the new page.

$.ajax({
 url: $('#FormID').attr('action'),
 type: 'POST',
 data: $('#FormID').serialize(),
 success: function (result) {
  window.location = result;
 }
});

here some doc info API jquery .serialize()



回答2:

"Unfortunately, looks like you can't redirect to another page after an Ajax form is submitted."

This is not entirely true. You can have your controller's action method return a url string that javascript redirects.

public string SomeMethod(ViewModel vm)
{
  ...
  return "http://www.google.com";
}

and in your view

$.ajax({
 url: "@(Url.Action("SomeMethod"))",
 type: 'POST',
 traditional: true,
 data: { ViewModel: jsonObject },
 success: function (result) {
  window.location = result;
 }
});


回答3:

You can redirect with javascript in your view that returns with the form submission... Something like this in the bottom of your view.

@if(Model.ShouldRedirect)
{
    <script type="text/javascript">
      window.location = '/path/to/new/url';
    </script>
}