Reputation: 2043
If a Model property name matches the name of a parameter passed into the Action, the value that is displayed on the view is that of the passed in parameter.
In the example below, the web page will display "red" as the color if the URL is /Car/Create?color=red. Even though the value on the Model is "Blue".
Is this the expected behavior?
Model:
namespace WebApplication1.Models
{
public class Car
{
public string Color { get; set; }
public Car(string color)
{
Color = color;
}
}
}
Controller:
public ActionResult Create(string color)
{
Car car = new Car("Blue");
return View(car);
}
View:
@model WebApplication1.Models.Car
@{
ViewData["Title"] = "Create";
}
<h1>Create</h1>
<h4>Car</h4>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Color" class="control-label"></label>
<input asp-for="Color" class="form-control" />
<span asp-validation-for="Color" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-primary" />
</div>
</form>
</div>
</div>
Upvotes: 4
Views: 518
Reputation: 27528
Yes, that is not a bug , it is side effect of ModelState
feature( using model binding and validation) that stores values it gets from request so in case of validation errors it can display the exact value that user entered . The related explanations here and here are for your reference .
You can manually clear the ModelState
:
ModelState.Clear();
Upvotes: 2