这是我第一次发布问题,我对Visual Studio2010还是个新手。我有一个web应用程序(用于学校作业),允许您创建一个“新闻项目”,将显示在首页。我已经完成了我的任务中的所有工作,除了我永远不能弄清楚当表单上的文本框为空时如何在我的表单上进行验证。我一直在到处寻找,并遵循了一些教程,但仍然无法让它在我的特定情况下工作。我在可视化设计器中找到我的数据库,右键单击它,然后单击“查看代码”,并将以下代码放入其中:
using System.ComponentModel.DataAnnotations;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace NewsDisplay
{
partial class NewsItemDataContext
{
}
[MetadataType(typeof(NewsItem_Validation))]
public partial class NewsItem
{
}
public class NewsItem_Validation
{
[Required(ErrorMessage = "Title is Required")]
public string Title { get; set; }
}
}
然后我的create函数在我的Homecontroller中,看起来像这样:
[HttpPost]
public ActionResult Create(FormCollection formData)
{
NewsItem n = new NewsItem();
if (ModelState.IsValid)
{
TryUpdateModel(n);
NewsItemRepository repository = new NewsItemRepository();
repository.AddNewsItem(n);
return RedirectToAction("index");
}
else
{
return View(formData);
}
}
一开始,我会在UpdateModel抛出一个异常,但后来我发现使用TryUpdateModel是可行的。现在,我在控制主页的.aspx代码中抛出了一个异常,因为新闻项目的标题不能为空。这是我的index.aspx页面,在我遇到异常的地方有一个注释:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumerable<NewsDisplay.NewsItem>>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Newest Stories</h2>
<% foreach (var item in Model) { %>
<table class="center">
<thead>
<tr>
<td>
<%= Html.ActionLink( item.Title, "Edit", new { id=item.NewsItemID } ) %> //this is where I get thrown the exception
</td>
</tr>
</thead>
<tbody>
<tr>
<td id="topRow">
<%: item.Date %>
</td>
</tr>
<tr>
<td id="bottomRow">
<%: item.Details %>
</td>
</tr>
</tbody>
</table>
<% } %>
</asp:Content>
我是在正确的轨道上吗?我已经查找了一段时间了,我似乎就是想不出如何让它适用于我的个人项目。提前感谢您的帮助!
发布于 2012-02-26 13:49:49
为什么你不在控制箱上使用验证器?您可以使用验证器并设置必须验证的控件,并在控件上定义错误消息
如果控件中数据无效,则页面不会发布
下面是一个例子
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="Write Error Message Here"></asp:RequiredFieldValidator>
解决了你的问题吗?
https://stackoverflow.com/questions/9453489
复制相似问题