4

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>
2
  • The example uses .NET Core 3.1 Commented Mar 11, 2020 at 23:44
  • I created another example app using .NET 4.7.2 which has the same behavior. I guess this is the expected behavior. Commented Mar 12, 2020 at 0:05

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.