What is the best way to fill the field of a datamodel instance using a form on a Razorpage? Is it possible to instantiate and submit a model directly from the Razorpage, or do i have to read each individual field of the form and assign them to a model instance in the controller?
Currently i am doing something like this: (not my actual code)
In the view:
<form method="post" action="some_action">
<input type="text" name="name" />
<input type="submit" value="submit" />
</form>
In the controller:
[HttpPost("some_action")]
Public IActionResult create_using_form()
{
person p = new person();
p.name = Request.Form["name"];
/*do whatever with person, like save to a db*/
return view();
}
I imagine there is a better solution, one where i dont have to populate every single field on my person object, one after the other. Any advice?
CodePudding user response:
You don't need to deal with each field in the form separately. Just use strongly typed view by defining the data model by using @model
.
Let say you have data model class DataModel
.
Then short way:
public IActionResult Index()
{
return View(new DataModel());
}
[HttpPost("some_action")]
public IActionResult create_using_form(DataModel model)
{
if (ModelState.IsValid)
{
//...
}
return View("Index", model);
}
The Html.EditorForModel()
helper was developed in ASP.NET Framework MVC, but it still has implementation in the ASP.NET Core MVC. The Html.EditorForModel()
returns an HTML input element for each property in the model.
@model DataModel
<form method="post" action="some_action">
@Html.EditorForModel()
<input type="submit" value="OK" />
</form>