Reputation: 45
Here is a strange issue I'm experiencing.
The model:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
The view:
@model Person
<div>
@Html.TextBoxFor(m => m.FirstName)
</div>
<div>
@Html.TextBoxFor(m => m.LastName)
</div>
The action:
public ActionResult Contact(string FirstName, string LastName)
{
// do something with FirstName and LastName passed in
var person = new Person();
person.FirstName = "John";
person.LastName = "Doe";
return View(person);
}
When call the action by:
/Home/Contact?FirstName=Jane&LastName=Smith
In the view it is Jane Smith where John Doe is expected. The view model is clearly the person.
But when the view modified to:
<div>
@Html.TextBox("First Name", Model.FirstName)
</div>
<div>
@Html.TextBox("Last Name", Model.LastName)
</div>
Everything is fine. Why is that? I'm on MVC 5.
Upvotes: 1
Views: 296
Reputation: 9131
That's how HTML Helper works. They will first look on the query parameters and use those values instead of using the on you specified on your Model on your controller.
For more info, you can see the same post here: Why is my MVC ViewModel member overridden by my ActionResult parameter?
Do you want to use your Model instead? Remove it on your Controller:
ModelState.Remove("FirstName");
ModelState.Remove("LastName");
var person = new Person();
person.FirstName = "John";
person.LastName = "Doe";
And it will render your desired Model
values.
Upvotes: 1
Reputation: 54
Its because of ambiguity. Rename the function parameters FirstName
to _FirstName
and LastName
to _LastName
. Then it will work as you expected.
public ActionResult Contact(string _FirstName, string _LastName)
Upvotes: 0