Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does model binding work via query string in asp.net mvc

Does model binding work via query string as well ?

If I have a get request like :

GET /Country/CheckName?Country.Name=abc&Country.Id=0 HTTP/1.1

Would the following method in CountryController have its oCountry argument containing Id and Name properties with values from the query string ?

public ViewResult CheckCountryName(Country oCountry)
{
     //some code
     return View(oCountry);
}

For some reason I am getting Id as 0 and Name as null in oCountry object. What is missing ?

like image 294
Brij Avatar asked Jun 26 '13 19:06

Brij


People also ask

How does model binding works in MVC?

Model binding is a well-designed bridge between the HTTP request and the C# action methods. It makes it easy for developers to work with data on forms (views), because POST and GET is automatically transferred into a data model you specify. ASP.NET MVC uses default binders to complete this behind the scene.

How data binding can be used in ASP.NET MVC?

ASP.NET MVC model binder allows you to map Http Request data with the model. Http Request data means when a user makes a request with form data from the browser to a Controller, at that time, Model binder works as a middleman to map the incoming HTTP request with Controller action method.

How does model binding work in asp net core application?

Model binding allows controller actions to work directly with model types (passed in as method arguments), rather than HTTP requests. Mapping between incoming request data and application models is handled by model binders.

Which component initiates the model binding process in MVC?

The action invoker, the component that invokes action methods, is responsible for obtaining values for parameters before it can invoke the action method. There can be multiple model binders in an MVC application, and each binder can be responsible for binding one or more model types.


1 Answers

Yes, the model binding supports binding from the query string. However the same model binding rules apply here also: the property names/expressions should match in your request and in your model.

So if you have a Name property then you need the have a Name key in the query string. If you write Country.Name the model binding first look for a property called Country and then a Name property on that country object.

So you don't need the Country prefix for you property names, so your request should look like this:

/Country/CheckName?Name=abc&Id=1 HTTP/1.1

Or if you cannot change the request you can specify the prefix for your action parameter with the BindAttribute:

public ViewResult CheckCountryName([Bind(Prefix="Country")]Country oCountry)
{
     //some code
     return View(oCountry);
}
like image 77
nemesv Avatar answered Sep 19 '22 17:09

nemesv