this is my first time ever posting a question and I am kind of new to Visual Studio 2010. I have a web application (for a school assignment) that allows you to create a "news item" that will be displayed on the front page. I have done everything in my assignment except I can't for the life of me figure out how to have valiadation on my form whenever a textbox on the form is left empty. I have been looking everywhere and have followed a few tutorials but still can't get it to work with my particular case. I went to my database in the visual designer, right clicked it and clicked "view code" and placed this in there:
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; }
}
}
And then my create function is in my Homecontroller and looks like this:
[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);
}
}
At first I would get thrown an exception at UpdateModel, but then I found that using TryUpdateModel works. Now I get thrown an exception at my .aspx code that controls the home page because the Title of the news item cannot be blank. Here is my index.aspx page with a comment at where I get the exception:
<%@ 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>
Am I even on the right track? I have been looking this up for a while now and I just can't seem to figure out how to make it work for my personal project. Thanks in advance for any help!