I am new to Asp.net MVC and developing an application having a form with 2 textboxes for input and 1 for output.I have added the buttons in the form as well.Now i want to display the output in the output textbox on click button event. Please let me know how can i do that in MVC4.
-
Please, before posting, have a look at the asp.net MVC tag and follow the docs and tutorial references.Alberto De Caro– Alberto De Caro2012-11-27 10:58:40 +00:00Commented Nov 27, 2012 at 10:58
-
possible duplicate of Button Event in ASP.NET MVCDonal Fellows– Donal Fellows2012-11-27 11:33:35 +00:00Commented Nov 27, 2012 at 11:33
1 Answer
ASP.NET MVC does not work the same as ASP.NET WebForms. Or rather, I should say ASP.NET WebForms does not work the same as the rest of the web(!).
When you create an HTML form is has an action attribute that specifies the URL that should handle the form submission. When the user submits the form, through an input or button with type="submit", the browser does a POST request to that URL, including the data contained in the form through using the application/x-www-form-urlencoded MIME type by default (different if the form should include file upload).
Your server-side code should not be responding to individual UI events as this is not how the web works, WebForms merely gave you an abstraction over HTTP to lure you into a sense of control that does not exist on the web.
Here is two example action methods that would handle the GET and POST requests for the form:
public ActionResult Index()
{
var model = new MyFormFields();
return View(model);
}
[HttpPost]
public ActionResult Index(MyFormFields fields)
{
if (!ModelState.IsValid)
{
return View(fields);
}
// do stuff with form data
var model = new MyResultModel
{
Output = fields.Input // for e.g.
};
return View("Results", model);
}
This responds to the form submission and renders a different view with the results view model. Best practice suggests doing an HTTP redirect here such that the browser can't resubmit the POST request by accident, but we'll leave that for later.