Home > Software engineering >  How textbox values are available in controller action method without model binding?
How textbox values are available in controller action method without model binding?

Time:05-27

I understand that when we bind the model to view then the textbox values will be available in the action methods.

@model SecurityDemoMVC.Models.UserModel

In Login view you can see there is no model binding. Textbox values are still available in Login action method when we use same property(username & Userpassword) name in textbox. How does it work when we don't bind a model to view?

enter image description here

Login.cshtml

enter image description here HomeController.cs

enter image description here UserModel.cs

CodePudding user response:

Html.TextBox is an extension, it still creates an input element with the name attribute matching the string which is passed into the method as a parameter InputExtensions.TextBox. Since it is contained in the form, it needs to match the name attribute with the endpoint parameter property name. Since, in your case, the name attribute is equal to your model's property name and the method is called correctly via the form the values are passed back into the controller.

All the Html helper methods do is convert your Razor into Html

Html.TextBox("someproperty", null, new{}); and Html.TextBoxFor(a => Model.someproperty, new {});, both create the equivalent of

<input name="someproperty" (if new {} != null, other attributes) />

MSDN Explanation of Model Binding:

Controllers and Razor pages work with data that comes from HTTP requests. For example, route data may provide a record key, and posted form fields may provide values for the properties of the model. Writing code to retrieve each of these values and convert them from strings to .NET types would be tedious and error-prone. Model binding automates this process. The model binding system:

Retrieves data from various sources such as route data, form fields, and query strings. Provides the data to controllers and Razor pages in method parameters and public properties. Converts string data to .NET types. Updates properties of complex types.

In short, Html Helper Methods Automate the process of creating the associated Html elements for you instead of you creating the Html elements yourself.

model-binding

CodePudding user response:

You might have passed the vales while calling the view it might have taken from there

  • Related