I am following the NerdDinner example, but creating my own project, and am having a problem with the [HttpPost]Create when using the ModelView pattern.
When I click Save with a blank form ModelState.IsValid is returning true and trying to save the blank object to the database.
Here are my model classes:
Code:
[MetadataType(typeof(Team_Validation))]
public partial class Team { }
public partial class Team
{
public Team()
{
this.createdBy = 9;
this.createdOn = DateTime.Now;
this.deleted_b = false;
}
}
public class Team_Validation
{
[Required(ErrorMessage = "Name is required")]
[StringLength(50, ErrorMessage = "Name may not be longer than 50 characters")]
string Name { get; set; }
[Required(ErrorMessage = "League is required")]
int LeagueId { get; set; }
}
public class TeamFormViewModel
{
FFRepository data = new FFRepository();
public Team Team { get; private set; }
public SelectList Leagues { get; private set; }
public TeamFormViewModel(Team team)
{
this.Team = team;
this.Leagues = new SelectList(data.GetLeagues(), "LeagueId", "ListName", Team.LeagueId);
}
}
Here is the aspx file:
Code:
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<FFAdminMvc.Models.TeamFormViewModel>" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Create New Team
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<h2>Create New Team</h2>
<% using (Html.BeginForm()) {%>
<%: Html.ValidationSummary(true) %>
<fieldset>
<div class="editor-label">
Team Name
</div>
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Team.Name)%>
<%: Html.ValidationMessageFor(model => model.Team.Name)%>
</div>
<div class="editor-label">
League
</div>
<div class="editor-field">
<%: Html.DropDownListFor(model => model.Team.LeagueId, Model.Leagues, "")%>
<%: Html.ValidationMessageFor(model => model.Team.Name) %>
</div>
<div>
<input type="submit" value="Create" />
</div>
</fieldset>
<% } %>
<div>
<%: Html.ActionLink("Back to List", "Index") %>
</div>
</asp:Content>
Here are the Create methods from the controller:
Code:
//
// GET: /Team/Create
public ActionResult Create()
{
Team team = new Team();
return View(new TeamFormViewModel(team));
}
//
// POST: /Team/Create
[HttpPost]
public ActionResult Create(Team team)
{
if (ModelState.IsValid)
{
data.AddTeam(team);
//data.Save();
return RedirectToAction("Details", new { id = team.TeamId });
}
else
{
return View(new TeamFormViewModel(team));
}
}
Any help with what I'm missing would be greatly appreciated.
Thanks,
Mike