这是我的观点的相关代码:
@Html.LabelFor(model => model.nickName)
@Html.TextBoxFor(model => model.nickName, new { @class = "RegisterControls" })
<br /><br />
@Html.LabelFor(model => model.email)
@Html.TextBoxFor(model => model.email, new { @class = "RegisterControls" })
<br /><br />
@Html.LabelFor(model => model.password)
@Html.TextBoxFor(model => model.password, new { @class = "RegisterControls" })
动作方法:
public ActionResult RegisterNewUser(string uName, string email, string password)
{
ViewBag.Message = "Register";
if (!users.RegisterUser(uName, email, password))
{
ViewBag.DeniedMsg = "A user with that email already exists";
return; //This doesn't work, as I should return a View
}
return PartialView("_Register");
}
如果用户在注册时键入已存在的电子邮件(并且单击显示&#34;创建帐户&#34;的链接,我只想添加一个标签,表明该电子邮件已存在,并且不返回整个视图。请参阅我的行动方法(希望)清晰。
创建帐户链接:
@Ajax.ActionLink("Create account", "CheckifUserEmailExists", "RegisteredUsers", new AjaxOptions { UpdateTargetId = "updaterDiv" }, new { @class = "actionButtons" })
实际上,更普遍。如果有人在文本框中输入内容,您将在适当的Controller中调用action方法。但是这个Action方法总是返回一个视图。但是,如果您只是想向该用户显示消息(例如,说&#34;创建帐户&#34;)并保持相同的视图,该怎么办?你怎么处理这个?我不能这样做,因为我必须返回一个视图,但我想保持相同的视图,并在那里显示消息
答案 0 :(得分:1)
再创建一个动作来返回字符串。像:
public string UserExistsMsg(string msg)
{
return msg;
}
并改变你的RegisterNewUser
行动:
public ActionResult RegisterNewUser(string uName, string email, string password)
{
ViewBag.Message = "Register";
if (!users.RegisterUser(uName, email, password))
{
return RedirectToAction("UserExistsMsg", "A user with that email already exists");
}
return PartialView("_Register");
}
答案 1 :(得分:1)
更改您的RegisterNewUser操作:
public ActionResult RegisterNewUser(string uName, string email, string password)
{
ViewBag.Message = "Register";
String msg = "";
if (!users.RegisterUser(uName, email, password))
{
msg = "A user with that email already exists";
}
ViewBag.DeniedMsg = msg;
return PartialView("_Register");
}
并在局部视图顶部打印ViewBag字符串消息。像:
@VeiwBag.DeniedMsg
如果用户不存在,则不会打印任何内容。