Creating my first creation page using ASP.Net MVC2

I am trying to create the first MVC application. I have a very simple table: Commands: ID, Name. I created an MVC application and the table is listed. Below is the Create View. When it starts, I get a message: value is required. Can you help (sorry, this is very simple).

View create.aspx:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<GettingStarted.Models.Team>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Create </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Create</h2> <%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %> <% using (Html.BeginForm()) {%> <fieldset> <legend>Fields</legend> <p> <label for="Name">Name:</label> <%= Html.TextBox("Name") %> <%= Html.ValidationMessage("Name", "*") %> </p> <p> <input type="submit" value="Create" /> </p> </fieldset> <% } %> <div> <%=Html.ActionLink("Back to List", "Index") %> </div> </asp:Content> 

with teamcontroller controller:

 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; using GettingStarted.Models; using DB = GettingStarted.Models.GettingStartedDataContext; namespace GettingStarted.Controllers { public class TeamController : Controller { // other actions ... // // GET: /Team/Create public ActionResult Create() { return View(); } // // POST: /Team/Create [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create(Team team) { if (ModelState.IsValid) { try { var db = new DB(); db.Teams.InsertOnSubmit(team); db.SubmitChanges(); return RedirectToAction("Index"); } catch { return View(team); } } return View(team); } } } 
+4
source share
3 answers

Your Create view is a strong type, so provide an instance of the view model:

 public ActionResult Create() { return View(new Team()); } 

or

 public ActionResult Create() { return View((Team)null); } 
+2
source

The problem may be a field annotation in the Model. You checked your model for something like:

 public class Team { [Required(ErrorMessage = "A value is required")] public string whatEver {get; set;} ... } 
+1
source

Hint: Add a Create action that takes the Team parameter as a parameter to handle validation errors.

 public ActionResult Create(Team team) { return View(team); } 

In addition, passing a null value to the creation form is not required! Your problem may be somewhere else. Can you try using

 <%= Html.TextBoxFor(model => model.Name) %> <%= Html.ValidationMessageFor(model => model.Name) %> 

instead

 <%= Html.TextBox("Name") %> <%= Html.ValidationMessage("Name", "*") %> 

?

0
source

All Articles