Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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";

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading