Reputation:
I'm working on an user register systems using ASP.Net MVC 4 and ADO.net (not EF).
I have this method in my BAL/BLL layer:
public static void InsertMemberUsername(RegisterRequest register, Guid id_fk)
{
if (Exist(register.UserName.Username))
{
// display error message to pick some other username
}
MEMBER_USERNAME entityToCreate = CreateMemberUsername(register, id_fk);
MEMBER_USERNAME_DAL.SQLAtlInsert(entityToCreate, "Server=ConnSting Here;");
}
In my controller I have this:
[CaptchaMvc.Attributes.CaptchaVerify("Captcha is not valid")]
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterRequest model)
{
if (ModelState.IsValid)
{
Membership_BAL.Register(model);
// TODO: Redirect user to profile page
return RedirectToAction("Index", "Home");
}
TempData["Message"] = "Error: captcha is not valid.";
return View();
}
The InsertMemberName method is called inside of the Register method.
What would be the best to display an error message if the username is already be used?
Upvotes: 0
Views: 1089
Reputation: 7105
There is obviously various ways to achieve this.
Modify your function from
public static void InsertMemberUsername(RegisterRequest register, Guid id_fk)
{
if (Exist(register.UserName.Username))
{
// display error message to pick some other username
}
MEMBER_USERNAME entityToCreate = CreateMemberUsername(register, id_fk);
MEMBER_USERNAME_DAL.SQLAtlInsert(entityToCreate, "Server=ConnSting Here;");
}
to
public static bool InsertMemberUsername(RegisterRequest register, Guid id_fk)
{
if (Exist(register.UserName.Username))
{
return false;
}
MEMBER_USERNAME entityToCreate = CreateMemberUsername(register, id_fk);
MEMBER_USERNAME_DAL.SQLAtlInsert(entityToCreate, "Server=ConnSting Here;");
return true;
}
I prefer to have a parameter within my model representing an error message and not to use TempData. Something like
public class SomeModel
{
public string ErrorMessage { get; set; }
// Your other model parameters go here.
}
Then you can set the parameter in your model like this
var someModel = new SomeModel();
if(!InsertMemberUsername( // You parameters))
{
someModel.ErrorMessage = "Error: captcha is not valid.";
}
And pass this model to your view like this
return View(someModel);
Within your view you can now display the contents of this parameter, for example
<div>
@if(!string.IsNullOrEmpty(@Model.ErrorMessage))
{
@Model.ErrorMessage
}
</div>
Upvotes: 1