Alert Javascript as return response of action

alert, asp.net-mvc-3, javascript

Solution

You could store the message inside `TempData` just before redirecting to the `Users` action:

TempData["message"] = "some message that you want to display";
return RedirectToAction("Users", "Admin");

and then inside the `Users.cshtml` view (which is returned by the `Users` action to which you redirected) test for the presence of this message and display an `alert`:

@if (TempData["message"] != null) {
    <script type="text/javascript">
        alert(@Html.Raw(Json.Encode(TempData["message"])));
    </script>
}

Problem

how can i do, for example, i create a user in users.cshtml view, that it validates to ActionResult Create(RegisterModel um) and if its all ok, i want to return at users.cshtml but always with one javascript alert or similar, with the value of a variable from the action. Can i do this one? I have it this in my view.. ``` @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>Crear Usuario</legend> <div class="editor-label"> Username: </div> <div class="editor-field"> @Html.TextBoxFor(model => model.UserName) @Html.ValidationMessageFor(model => model.UserName) </div> <div class="editor-label"> Password: </div> <div class="editor-field"> @Html.PasswordFor(model => model.Password) @Html.ValidationMessageFor(model => model.Password) </div> <div class="editor-label"> Repite Password: </div> <div class="editor-field"> @Html.PasswordFor(model => model.ConfirmPassword) @Html.ValidationMessageFor(model => model.ConfirmPassword) </div> </div> <p> <input type="submit" value="Crear" /> </p> </fieldset> ``` And this in my controller action.. ``` public ActionResult Create(RegisterModel um) { if (um.Password == um.ConfirmPassword) { // Attempt to register the user MembershipCreateStatus createStatus; Membership.CreateUser(um.UserName, um.Password, um.Email, um.PasswordAnswer, um.PasswordQuestion, true, null, out createStatus); if (createStatus == MembershipCreateStatus.Success) { var alert = MembershipCreateStatus.Success.ToString(); } else { ModelState.AddModelError("", ErrorCodeToString(createStatus)); var alert = ErrorCodeToString(createStatus); } } //HERE IS WHERE I WANT TO RETURN TO /ADMIN/USERS BUT WITH AN ALERT WITH CONTAINING THE VALUE OF alert IN A JAVASCRIPT OR SIMILAR ALERT WINDOW return RedirectToAction("Users", "Admin"); ??????? ``` Can i do it something like this?

Original source

Related problems