0

I have a set of PartialView that are dynamicaly changed in a page. A PartialView loads the next and so on using ajax. One of them have a form of like 20 inputs, currently I'm just sending one input but how can I send the rest of them? I have this in this partialview:

var shipping= $("input[name='shipping']:checked").val()
    $.ajax(
      {
          url: '/Home/Payment',
          type: "POST",
          data: { 'shipping': shipping},
          success: function (data) {
              $("#cart").html(data);

          }
      });

And this in the controller:

public ActionResult Payment(string shipping)
    {
        **do stuff*
        return PartialView("NextPartialView");
    }

The controller recieves every input of the form but as I said before there are 20 of them. Is there a way to keep the code clean and readable using another technique to send the data?

I'm new in MVC and razor

Thanks

0

2 Answers 2

1

Use JSON model binding. This post can help you get the picture.

In short, create javascript object with property names matching model. Send it to controller and it will be bound. Also, note that numbers are better to be sent as strings (look at this).

Sign up to request clarification or add additional context in comments.

Comments

0

Have your Items in a Form and serialize the form and send to the action method.

@model YourSomeViewModel
@using(Html.Beginform())
{
  FirstName :   @Html.TextBoxFor(x=>x.FirstName)
  LastName:   @Html.TextBoxFor(x=>x.LastName)
  Location :   @Html.TextBoxFor(x=>x.Location)
  Is Available to hire @Html.CheckBoxFor(x=x.IsAvailable)
  <input type="submit" id="btnSubmit" />
}

Now in your script

$(function(){
  $("#btnSubmit").click(function(e){
    $.post("@Url.Action("Save","YourControllerName")", 
                          $(this).closest("form").serialize(), function(data){
            //do something with the response
    });    
  });  
});

Now your action method parameter will be your view model class. Mvc Model binding will map the posted (serialized) form data to an instance of your view model class.

[HttpPost]
public ActionResult Save(YourSomeViewModel model)
{
   //check model properties now

  //saved and respond /redirect
}

Comments

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.