In an ASP. NET MVC application, the data submitted by the form is passed from view to the controller through model binding. It is much easier to use model bindings than request.form["Price", Decimal.Parse (request.form["price"), and also require manual type conversions.
There are two types of model bindings, implicit binding and explicit binding.
1, implicit model binding. The form value is first converted to a CLR type, and then the form field name name, value parameter is passed to the action. To prevent over-committing, use the bind (Include) attribute to accept the whitelist, and the bind (exclude= ") attribute rejects the blacklist.
Post:movie/create
To prevent an "excessive publishing" attack, enable the specific property you want to bind to,
For more information, see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[Validateantiforgerytoken]
Public ActionResult Create ([Bind (Include = "Id,title,releasedate,genre,price")] movie Movie)
{
if (modelstate.isvalid)
{
db. Movies.add (movie); Set the tracking state of the entity to entitystate.added, or in the edit operation, you need to set the entitystate.modified manually;
Db. SaveChanges ();
Return redirecttoaction ("Index");
}
return View (movie);
}
2. Explicit binding uses TryUpdateModel and Updatemodel explicit binding, which automatically sets the tracking entity state of the database context object to enritystate.modified. You can also specify a bound field by setting a parameter, the difference is that if the binding fails, the former does not throw an exception, which throws an exception.
[HttpPost]
[ActionName ("Edit")]
[Validateantiforgerytoken]
Public ActionResult editpost (int? id)
{
if (id = = NULL)
{
return new Httpstatuscoderesult (httpstatuscode.badrequest);
}
var studenttoupdate = db. Students.find (ID);
if (TryUpdateModel (Studenttoupdate, "", new string[] {"LastName", "Firstmidname", "EnrollmentDate"}))
{
Try
{
The following statement is not required to set the database context to track the state of the entity, and the entitystate.modified tag for tracking status has been set automatically
Db. Entry (studenttoupdate). state = entitystate.modified;
Db. SaveChanges ();
Return redirecttoaction ("Index");
}
catch (dataexception/* dex*/)
{
Log the error (uncomment DEX variable name and add a line here to write a log.
Modelstate.addmodelerror ("", "cannot save changes, try again, if the problem persists, contact your system administrator");
}
}
Return View (studenttoupdate);
}
Model bindings in ASP.