Explain Model Binding in ASP.NET Core with exqample.
Model Binding in ASP.NET Core
- The Model Binding extracts the data from an HTTP request and provides them to the controller action method parameters. The action method parameters may be simple types like integers, strings, etc. or complex types such as Student, Order, Product, etc.
- The controller action method handle the incoming HTTP Request.
- Our application default route template ({controller-Home}/{action=Index}/{ld?})
- When you load this url - http://localhost:52191/home/details/101, shows the Details action method.
public ViewResult Details(int Id)
var student Details= listStudents. FirstOrDefault(std => std. StudentId == Id); return View(studentDetails);
Example
In Model Folder, create a class WebUser.cs public class WebUser {
public string FirstName { get; set; }
public string LastName { get; set; }
}
In Controller Folder, create a new Controller as UserController.cs and add action method as follows:
[HttpGet]
public IActionResult SimpleBinding() {
return View(new WebUser() { FirstName = "John", LastName = "Doe" }); }
By letting our View know what kind of Model it can expect, with the @model directive, we can now use various helper methods (more about those later) to help with the generation of a FORM:
In View Folder, create a file SimpleBinding.cshtml @using (var form = Html. BeginForm())
{
<div>
@Html. LabelFor (m => m. FirstName)
@Html.TextBoxFor (m => m.FirstName)
</div>
<div>
@Html. LabelFor (m => m. LastName)
@Html. TextBoxFor (m => m. LastName)
</div>
<input type="submit" value="Submit" /> }
The result will be a very generic-looking FORM, but with labels and textboxes designated to host the properties of your Model:
FirstName John
LastName Doe
Submit
By default, the FORM will be posted back to the same URL that delivered it, so to handle that, we need a POST-accepting Controller method to handle the FORM
submission: [HttpPost]
public IActionResult SimpleBinding (WebUser webUser)
{
//TODO: Update in DB here...
return Content ($"User [webUser. FirstName} updated!");
}
Comments
Post a Comment