简体   繁体   中英

How do I save my MVC4 model if I need 2 submit buttons?

I have to allow the user to move to the next or previous form, I just need to save the model on navigation. Is there another way to pass back the model to the controller besides using submit? Since I need to redirect to other possible pages.

You could put your model object in the TempData collection on submit, redirect, then read it back out again. For example:

[HttpPost]
public ActionResult FirstForm(FirstFormModel model) {
    TempData["TempModelStorage"] = model;
    return RedirectToAction("SecondForm");
}

public ActionResult SecondForm() {
    var firstModel = TempData["TempModelStorage"] as FirstFormModel;
    // check for null, use as appropriate, etc.

    return View(...);
}

More details here: http://msdn.microsoft.com/en-us/library/dd394711(v=vs.100).aspx

You may save the data asynchronously using jQuery ajax on those button click events.

Assuming your View is something like this

@using(Html.BeginForm("Save","Items"))
{
  <div>
    Name :  @Html.TextBoxFor(s=>s.Name)
    <input type="button" class="navigBtns" value="Prev" />
    <input type="button" class="navigBtns" value="Next" />
 </div>
}

And your script is

$(function(){

 $(document).on("click",".navigBtns",function() {
   e.preventDefault();
   var _this=$(this);
   $.post(_this.closest("form").attr("action"), _this.closest("form").serialize(),
                                                                         function(res){
      //check res variable value and do something as needed
      //  (may be redirect to another page /show/hide some widgets)
   });
 });

});

Assuming you have an action method called Save in your controller to handle the saving part.

Was given a neat article about this.

MVC Wizard Example

Basically this, you literally pass the name of the html button.

In the view form

<input type="submit" name="btnPrev" />
<input type="submit" name="btnNext" />

In the Controller Controller

    public ActionResult DoStuff(ModelClass mc,string btnPrev,string btnNext)
{
  string actionString = "previousPage";
  if(btnNext != null)
     actionString = "nextPage";


  return RedirectToAction(actionString,"Controller")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM