Search code examples
asp.net-mvcrazorrazor-2

Model after post not change why


I have Page for Both Insert User and this work fine but after I insert new info i send new model but this not work.the info that i insert before are still in textbox without any error. why???

return View(new User());

@using (@Html.BeginForm("RegisterUser", "UserManagement", FormMethod.Post))
{
    @Html.AntiForgeryToken()

    <table class="Registertbl">
        <tr>
            <td>نام*</td>
            <td> @Html.TextBoxFor(m => m.FName, new { maxlength = 20})<br />
            </td>               
            <td>سمت*</td>
            <td>@Html.TextBoxFor(m => m.Post, new { maxlength = 200})</td>                
        </tr>
    </table>
    <br />
        <input type="submit" value="Insert" class="insertBtn" />
        @Html.ActionLink("back", "ViewUserList", "UserManagement")
}

//Controller

 [HttpGet]
    public ActionResult RegisterUser()
    {
        return View(new User());
    }
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult RegisterUser(Common.UsersManagement.Entities.User model)
    {
        SetUserManagement();
        var Result = userManagement.RegisterUser(model);
        if (Result.Mode == Common.Extensions.ActionResultMode.Successfully)
        {
                return View(new User());
        }
         // if not Successfull
        return View(model);
    }

Solution

  • maf748 is correct, you should Post-Redirect-Get. You can communicate to the GET action method using TempData that a message should be displayed, e.g.

    TempData.Message = "User registered.";
    return RedirectToAction( "RegisterUser" );
    

    Then in your RegisterUser view you can check if TempData.Message has a value.

    However, if after all that you still want do do it your way you could try ModelState.Clear() before returning the new View. The problem this will cause is that if the user refreshes the page in their browser it will send them back to your Post method, prompting them in the browser with that awful "do you want to resubmit your data" message and potentially creating duplicate registrations in your database.