Reputation: 1782
This is the relevant code of my View:
@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" })
And Action method:
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");
}
If a user types in an already existing email upon registering (and when clicking the link that says "Create account", I want to just add a label saying that the email already exists, and NOT returning an entire view. See my action method for (hopefully) clearity.
The create account link:
@Ajax.ActionLink("Create account", "CheckifUserEmailExists", "RegisteredUsers", new AjaxOptions { UpdateTargetId = "updaterDiv" }, new { @class = "actionButtons" })
Actually, more generally. If someone types in something in a text box, you will call the action method in the proper Controller. But this Action method always returns a view. But what if you just want to display a message to that user (e.i. saying "account created") and staying on the same view. How do you handle this? I can't do this, since I have to return a view, but I want to stay on the same view, and display the message there
Upvotes: 0
Views: 608
Reputation: 1249
Change your RegisterNewUser action like this:
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");
}
And print the ViewBag string message at the top of partial view. Like:
@VeiwBag.DeniedMsg
If user doesn't exist, nothing will get printed.
Upvotes: 1
Reputation: 1249
Create one more action to return string. Like:
public string UserExistsMsg(string msg)
{
return msg;
}
And change your RegisterNewUser
action like this:
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");
}
Upvotes: 1