I have a simple form based off a model called Visitor. I'd like to have a search button by one of the id text fields so the user can click the button and have the page populate with visitor information: first name, last name, etc. In Web Forms I would do something like this:
page_load(){
person = businessManager.FindPersonById(Convert.ToInt32(txtId.Text));
txtFirstName.Text = person.FirstName;
txtLastName.Text = person.LastName;
...
}
Prior to the search button, my view form called SignIn worked just fine; posted the data to the controller and did its thing:
[HttpPost]
public ActionResult SignIn(Visitor visitor) {
if (ModelState.IsValid) {
visitorRepoistory.Add(visitor);
visitorRepoistory.Save();
return RedirectToAction("/");
} else {
return View(new VisitorFormViewModel(visitor));
开发者_高级运维 }
}
But now that I have a search button placed on my view form, I'm totally lost. I don't know how to wire the search button to the controller so I can: 1.) Look up the data and 2.) Return it back to the sign in form to populate the fields. What are the steps I need to take to accomplish this?
Thanks.
This question has been duplicated many times on SO
Multiple forms in ASP.NET MVC
But to answer your question you can have multiple forms on one page and have different Actions handle the submits. That's what the link above outlines.
Specific to your case:
View
<% Html.BeginForm("Search", "<ControllerName>"); %>
Your search controls here
<% Html.EndForm(); %>
<% Html.BeginForm("SignIn", "<ControllerName>"); %>
Your signin controls here
<% Html.EndForm(); %>
Controller
[HttpPost]
public ActionResult Search(FormCollection collection)
{
Do your search and return a view
}
[HttpPost]
public ActionResult SignIn(Visitor visitor)
{
if (ModelState.IsValid) {
visitorRepoistory.Add(visitor);
visitorRepoistory.Save();
return RedirectToAction("/");
} else {
return View(new VisitorFormViewModel(visitor));
}
}
精彩评论