Response.Write
在您的控制器中,它不会对视图做任何事情。
您应该将模型返回到“编辑”页面,其中有任何错误
ModelState.AddModelError();
这里有一个非常好的示例,说明了如何实现存储库模式,以及如何利用中的ASP.NET MVC模型绑定功能等
NerdDinner Chapter
来自专业的ASP.NETMVC书籍。
//
// POST: /AdminAlbums/Create
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create(FormCollection collection)
{
var album = new Album();
// Method on System.Web.Mvc.Controller, that takes a form collection, and
// using reflection on the Model, assigns values to it from the form.
UpdateModel(album);
if (album.IsValid)
{
// These methods are the same as yours
m_PhotoRepository.Add(album);
m_PhotoRepository.Save();
// In this instance, I'm returning the user to a list view of Albums
// for editing, probably ought to send them to the page to start
// uploading photos.
return RedirectToAction("Index");
}
// Still here, so I'm going to set up some ViewData I need.
ViewData["Title"] = "Create a new album";
ViewData["Message"] = "Create Album";
// I'm picking up errors from the model here.
// RuleViolation is my own class, implemented in a partial on Album.
foreach (RuleViolation violation in album.GetRuleViolations())
{
ModelState.AddModelError(violation.PropertyName, violation.ErrorMessage);
}
return View(album);
}
因此,您可以看到,如果出现错误,我会将模型返回到主视图,以填充验证摘要。
该观点的相关部分是:
<%= Html.ValidationSummary("Edit was unsuccessful. Please correct the errors and try again.") %>
<% using (Html.BeginForm()) {%>
<fieldset>
<legend>Album details</legend>
<div class="form_row">
<label for="Caption" class="left_label">Album caption:</label>
<%= Html.TextBox("Caption", Model.Caption, new { @class = "textbox" })%>
<%= Html.ValidationMessage("Caption", "*") %>
<div class="cleaner"> </div>
</div>
<div class="form_row">
<label for="IsPublic" class="left_label">Is this album public:</label>
<%= Html.CheckBox("IsPublic", Model.IsPublic) %>
</div>
<div class="form_row">
<input type="submit" value="Save" />
</div>
</fieldset>
<% } %>
对不起,我应该澄清一下:
这其中很多都是基于使用ASP.NETMVC框架提供的助手方法——您会注意到我使用的方法如下
Html.TextBox
要生成我的字段,请使用从模型本身提取的名称/id。这样,如果在ModelState中加载带有ModelErrors的视图,助手将向呈现的HTML添加相关细节,以包括以下标记
<label for="Caption" class="left_label">Caption:</label>
<input class="input-validation-error textbox"
id="Caption" name="Caption" type="text" value="" />
<span class="field-validation-error">*</span>
您可以选择的另一个选项是将消息添加到
ViewData
集合,如果它有值,则在视图上显示该值。
要记住以下几点:
1) 表单元素和验证控件的标识符应相同:
<%= Html.TextBox("Caption", Model.Caption, new { @class = "textbox" })%>
<%= Html.ValidationMessage("Caption", "*") %>
(你有“用户电子邮件”和“电子邮件”之类的东西)
2) 您应该在出错时将hdUser返回到视图-因此请尝试以下操作:
<AcceptVerbs(HttpVerbs.Post)> _
Public Function NewUser(ByVal formValues As FormCollection) As ActionResult
Dim user = New hdUser()
Try
UpdateModel(user)
user.isLive = 1
user.avatar = "noavatar.gif"
userRepository.Add(user)
userRepository.Save()
Catch ex As Exception
ModelState.AddModelError("Error", ex)
End Try
Return View(user)
End Function