asp.net-coreasp.net-core-mvcpostback

ASP.NET Core MVC - Not binding to fresh model during postback


I am unable to return the updated view in the "Save" POST method, even after updating model data and calling View("Index", newPerson). What is causing this behavior? Is it ASP.NET Core or the web browser causing this behavior?

If I type a new value in the browser, say name, it is retaining that value, but it is not binding with the new Name value I have set in the Save method.

newPerson.Name = newPerson.Name + " Added";

Here is my simple controller:

public class PersonController : Controller
{
    public PersonController()
    {

    }

    public IActionResult Index()
    {
        Person p = new() { Id = 1, Age = 5, Name = "Sooo" };

        return View(p);
    }

    [HttpPost]
    public IActionResult Save(Person newPerson)
    {
        newPerson.Name = newPerson.Name + " Added";
        return View("Index", newPerson);
    }
}

Here is my view Index.cshtml:

@model Person

<form action="/Person/Save" method="post">

    <table>
        <tr>
            <td>First Name: </td>
            <td><input type="text" asp-for="@Model.Name"  /></td>
        </tr>
        <tr>
            <td>Age: </td>
            <td><input type="text" asp-for="@Model.Age"/></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Submit" /></td>
        </tr>
    </table>

</form>

Solution

  • You need to bind the value with the value attribute.

    <input type="text" asp-for="Name" value="@Model.Name"  />
    
    <input type="text" asp-for="Age" value="@Model.Age" />
    

    enter image description here