Search code examples
asp.net-core-mvcpostback

Asp.Net core mvc - not binding to fresh model during postback


I am unable to return updated view in "Save" post method, even after updating model data and calling View("Index", newPerson). - What is causing this behavior? Is it asp.net core or web browser causing this behavior.

If I type new value in browser say name, it is retaining that value, but it is not binding to new "Name" I have set in "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>

Thank you for your help.

V


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