Domanda

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);
    }
È stato utile?

Soluzione

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.

Altri suggerimenti

Try redirecting back to the GET RegisterUser.

The reason is: when you submit a form to MVC, all the values in the ModelState (basically the Request values) take precedence over any model you pass to the view. The redirect will give you an empty ViewDataDictionary, so all values will be pulled from the Model you're passing (the new User())

if (Result.Mode == Common.Extensions.ActionResultMode.Successfully)
{
    return RedirectToAction("RegisterUser");
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top