我该怎么办,例如,我在users.cshtml视图中创建一个用户,它验证ActionResult Create(RegisterModel um),如果一切正常,我想在users.cshtml返回,但总是用一个javascript警报或类似的,具有来自操作的变量的值。我可以这样做吗?
在我看来,我有这个......
@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>
这是我的控制器动作..
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"); ???????
我可以这样做吗?
答案 0 :(得分:8)
您可以在重定向到TempData
操作之前将邮件存储在Users
内:
TempData["message"] = "some message that you want to display";
return RedirectToAction("Users", "Admin");
然后在Users.cshtml
视图内(由您重定向的Users
操作返回)测试是否存在此消息并显示alert
:
@if (TempData["message"] != null) {
<script type="text/javascript">
alert(@Html.Raw(Json.Encode(TempData["message"])));
</script>
}
答案 1 :(得分:0)
我试图在同一视图中显示错误,而不是尝试使用darin的答案我尝试使用ViewBag
和this之类的其他人通过返回{{1}在另一页中显示错误}}
最后我尝试使用Partial View
,在发布期间维护消息,这里我使用bootstrap显示错误
操作方法:
TempData
我的注册视图:
[HttpPost]
public ActionResult RegDetail(User_table usob, FormCollection col)
{
// some other code here
if (!sqlReader.HasRows)
{
TempData["message"] = "Contains some message";
return RedirectToAction("Registration");
}
return RedirectToAction("Index");
}
如果你需要使用Tempdata探索更多,你可以查看this Mr.James使用bootstrap消息解释的地方,希望能帮助某人