Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

c# - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...