我使用的是ASP MVC 4.0,我想了解自定义验证的基础知识。在这种特殊情况下,模型根本不是强类型的控制器或视图,所以我需要一些不同的类型。
我想要做的是在注册到我的服务时接受一个新的用户名,在数据库中查找,并在该用户名被使用的情况下重新显示原始表单。
这是我的输入表单:
@{
ViewBag.Title = "Index";
}
<h2>New account</h2>
<form action= "@Url.Action("submitNew", "AccountNew")" method="post">
<table style="width: 100%;">
<tr>
<td>Email:</td>
<td> </td>
<td><input id="email" name="email" type="text" /></td>
</tr>
<tr>
<td>Password:</td>
<td> </td>
<td><input id="password" name="password" type="password" /></td>
</tr>
<tr>
<td>Confirm Password:</td>
<td> </td>
<td><input id="passwordConfirm" name="passwordConfirm" type="password" /></td>
</tr>
<tr>
<td></td>
<td> </td>
<td><input id="Submit1" type="submit" value="submit" /></td>
</tr>
</table>
</form>下面是我提交时的控制器方法:
public ActionResult submitNew()
{
SomeService service = (SomeService)Session["SomeService"];
string username = Request["email"];
string password = Request["password"];
bool success = service.guestRegistration(username, password);
return View();
}如果成功是假的,我只想用一条消息重新显示表单。我缺少这个错误流的基础知识。你能帮帮忙吗?提前谢谢。
发布于 2013-02-12 04:30:31
您可以添加一个ViewBag项
bool success = service.guestRegistration(username, password);
if (!success)
{
ViewBag.Error = "Name taken..."
}
return View();但是你应该创建一个视图模型...
public class ViewModel
{
public string UserName {get; set;}
//...other properties
}...strongly输入你的视图并使用内置的html助手...
@model ViewModel
//...
@using BeginForm("SubmitNew", "AccountNew", FormMethod.Post)()
{
//...
<div>@Html.LabelFor(m => m.Username)</div>
<div>@Html.TextBoxFor(m => m.Username)</div>
<div>@Html.ValidationMessageFor(m => m.Username)</div>
}...and在控制器中利用ModelState
[HttpPost]
public ActionResult SubmitNew(ViewModel viewModel)
{
if(ModelState.IsValid)
{
SomeService service = (SomeService)Session["SomeService"];
bool success = service.guestRegistration(viewModel.username, viewModel.password);
if (success)
{
return RedirectToAction("Index");
}
ModelState.AddModelError("", "Name taken...")"
return View(viewModel);
}
}...or甚至编写自己的验证器,只需修饰模型属性,就不需要在控制器中检查是否成功。
https://stackoverflow.com/questions/14820233
复制相似问题