PilgrimViis PilgrimViis - 2 months ago 6
C# Question

Send two forms with one button and than redirect to third action

Is it possible to submit simultaneously 2 forms to different actions? In the actions I want to set TempData and than redirect to third action.

I tried method described here Submit two forms with one button Let's suggest that each form have one input field. First form with "name" input, second with "lastname" input

submitForms = function(){
document.forms["formForFirstAction"].submit();
document.forms["formForSecondAction"].submit();
window.location("/Home/ThirdAction")
}


My Actions looks like...

[HttpPost]
public void FirstAction(string name) {
TempData["name"] = name;
}
[HttpPost]
public void SecondAction(string lastname) {
TempData["lastname"]=lastname;
}
public ActionResult ThirdAction () {
string fullname;
fullname = string.Format((string)TempData["name"] +
(string)TempData["lastname"]);
return View(fullname);
}


But it doesn't work. In most cases I got only name or last name in fullname string. Looks like it's something with async or other things I don't know much now. Can you please help me?

Answer

TempData is available only the next immediate request. That is the reason you are getting only one item (the last one set from one of those 2 action methods) from the temp data dictionary. You should consider using another persistence mechanism like Session /database

Also, Instead of submitting the form, you oshould consider ajax

submitForms = function(){
   $.post("@Url.Action("FirstAction")",$("#formForFirstAction").serialize());
   $.post("@Url.Action("SecondAction")",$("#formForSecondAction").serialize());
   window.location("/Home/ThirdAction")
}

and here is an example using Session to persist data

[HttpPost]
public void SecondAction(string lastname) {
    Session["lastname"]=lastname;
}
public ActionResult ThirdAction () {
    string fullname;
    fullname = string.Format((string)Session["name"] + 
    (string)Session["lastname"]);
    return View(fullname);
}

You may also consider using jquery when() or q.all to make sure that you are redirecting only after the ajax call's are done ( to avoid the callback hell)