Validation for unique username not working in ASP.NET MVC4 - c#

I trying to validate username for uniqueness but due to some reasons its not working fine. I am doing it in the following way
MODEL
public class System_User
{
public int Id { get; set; }
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required]
[Remote("doesUserNameExist", "System_User", HttpMethod = "POST", ErrorMessage = "User name already exists. Please enter a different user name.")]
public string UserName { get; set; }
[Required]
[DataType(DataType.Password)]
public string Password { get; set; }
public bool IsAdmin { get; set; }
}
Controller
I have added the following code to my System_User Controller
[HttpPost]
public JsonResult doesUserNameExist(string UserName)
{
var user = Membership.GetUser(UserName);
return Json(user == null);
}
View
I have the default create view generated by mvc with necessary references to jquery
#model WhiteBoard.Models.System_User
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<table class="userTable">
<tr>
<td>
#Html.LabelFor(model => model.FirstName)
</td>
<td>
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.LastName)
</td>
<td>
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.UserName)
</td>
<td>
#Html.EditorFor(model => model.UserName)
#Html.ValidationMessageFor(model => model.UserName)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.Password)
</td>
<td>
#Html.EditorFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.IsAdmin)
</td>
<td>
#Html.EditorFor(model => model.IsAdmin)
#Html.ValidationMessageFor(model => model.IsAdmin)
</td>
</tr>
<tr>
<td colspan="2">
<input class="btn btn-success" type="submit" value="Create User" />
</td>
</tr>
</table>
}
<div>
<p>
#Html.ActionLink("Back to List", "Index")
</p>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
}
When I ran the application, it neither threw an exception nor the validation worked.
May I know where am I making a mistake

Looks like an issue is:
return Json(user == null);
If the user is null, you will return true when you want to return false, the user does not exists. Change it to
return Json(user != null);
If that doesn't work or if the == was just a type please let us know in the comments what username you entered, what the expected result was, and what the actual result was.

Related

Best practice to display values after submitting form in ASP.NET MVC

I am quite new to ASP.NET and MVC and I'm currently trying the following:
Model: Properties of the form
View: Display a form to the user
Controller:
Action: Do something
Go back to initial view and display values to user
With normal html I got this to work. With razor syntax I so far did not manage to re-display the values after the form was submitted.
My model:
namespace MyModels
{
public class SubmitTicketFormModel
{
[DisplayName("First Name")]
public string _firstName { get; set; }
[DisplayName("Last Name")]
public string _lastName { get; set; }
}
}
My View:
#model MyModels.SubmitTicketFormModel
#{
ViewData["Title"] = "SubmitTicketView";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Request</h1>
#using (Html.BeginForm("SubmitTicketAction", "SubmitTicketContoller", FormMethod.Post))
{
<div class="form-group">
#Html.LabelFor(model => model._firstName)
#Html.TextBoxFor(model => model._firstName, new { #class = "form-control" })
#Html.LabelFor(model => model._lastName)
#Html.TextBoxFor(model => model._lastName, new { #class = "form-control" })
</div>
<input type="submit" value="Post comment" />
}
<table class="table table-bordered table-sm">
<thead class="thead-light">
<tr>
<th>col1</th>
<th>col2</th>
</tr>
</thead>
<tbody>
<tr>
<td>
#Model._firstName
</td>
<td>
#Model._lastName
</td>
</tr>
</tbody>
</table>
Controller:
public class SubmitTicketController : Controller
{
public ActionResult SubmitTicketView()
{
var TicketInstance = new SubmitTicketFormModel();
return View(TicketInstance);
}
[HttpPost]
public ActionResult SubmitTicketAction(SubmitTicketFormModel model)
{
var NewTicketInstance = new SubmitTicketFormModel()
{
_firstName = model._firstName,
_lastName = model._lastName
};
return View(NewTicketInstance);
}
}
}
Can you please guide me in the right direction?
If you want the same View to render after the user clicks on submit button, then I guess you don't want that #using (Html.BeginForm("SubmitTicketAction", "SubmitTicketContoller", FormMethod.Post)) in the UI to show up again. Only the values of first name and last name in your view of which you've written your logic down in your view.
In that case, you can just pass a ViewBag in your view from controller which will help your View understand whether it has to show the input form or display user's entered data.
[HttpPost]
public ActionResult SubmitTicketAction(SubmitTicketFormModel model)
{
var NewTicketInstance = new SubmitTicketFormModel()
{
_firstName = model._firstName,
_lastName = model._lastName
};
ViewBag.Check = "true";
return View(ViewName , modelname);
}
And then in your view,
#model MyModels.SubmitTicketFormModel
#{
ViewData["Title"] = "SubmitTicketView";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#if(ViewBag.Check != null)
{
<h1>Request</h1>
#using (Html.BeginForm("SubmitTicketAction", "SubmitTicketContoller", FormMethod.Post))
{
<div class="form-group">
#Html.LabelFor(model => model._firstName)
#Html.TextBoxFor(model => model._firstName, new { #class = "form-control" })
#Html.LabelFor(model => model._lastName)
#Html.TextBoxFor(model => model._lastName, new { #class = "form-control" })
</div>
<input type="submit" value="Post comment" />
}
}
else
{
<table class="table table-bordered table-sm">
<thead class="thead-light">
<tr>
<th>col1</th>
<th>col2</th>
</tr>
</thead>
<tbody>
<tr>
<td>
#Model._firstName
</td>
<td>
#Model._lastName
</td>
</tr>
</tbody>
</table>
}

How can I view both table and form in same view

I have recently learning ASP.NET MVC5.
I am trying to see both the form and a table(return as partialview) in one view but i'm getting this error.
System.NullReferenceException: Object reference does not set to an instance of an object.
Here is my Model:
public class Prescription
{
[Key]
public int PrescriptionID { get; set; }
[ForeignKey("Assessment")]
public int? AssessmentID { get; set; }
public Assessment Assessment { get; set; }
[ForeignKey("Medicine")]
[Display(Name ="Prescription")]
public int? MedcineID { get; set; }
public Medicine Medicine { get; set; }
}
My main view where I want to put my partial view:
#using ClinicManagemet
#model ClinicManagemet.Models.Prescription
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Prescription</h4>
<hr />
<div class="form-group">
#Html.LabelFor(model => model.MedcineID, "MedcineID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("MedcineID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.MedcineID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
#Html.Action("ViewPrescription","Assessments")
<div>
#Html.ActionLink("Back to Home", "Home")
</div>
My partial view:
#model IEnumerable<ClinicManagemet.Models.Prescription>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Assessment.Complaint)
</th>
<th>
#Html.DisplayNameFor(model => model.Medicine.MedicineName)
</th>
<th></th>
</tr>
#foreach (var item in Model) { //Here is the line where I get the error
<tr>
<td>
#Html.DisplayFor(modelItem => item.Assessment.Complaint)
</td>
<td>
#Html.DisplayFor(modelItem => item.Medicine.MedicineName)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.PrescriptionID }) |
#Html.ActionLink("Details", "Details", new { id=item.PrescriptionID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.PrescriptionID })
</td>
</tr>
}
</table>
My partial view's controller:
public ActionResult ViewPrescription()
{
return PartialView();
}
Edit: If I fix this, I'll try to add Ajax so whenever I insert something, it will just refresh the partial view.
Load your partial view like this,
#{
Html.RenderAction("ViewPrescription","YourControllerName")
}
And in your ViewPrescription method, return the data,
{
//Fetch the data here
return PartialView(model);
}
Hope it helps.
You're not passing a model into the partial view when returning the view.
public ActionResult ViewPrescription()
{
ClinicManagemet.Models.Prescription model = _service.GetPerscription();
return PartialView(model);
}

MVC Passing a Complex Object to the controller for saving

I am writing a web page with MVC and Entity Framework.
I have an order with line items attached and want to return a complex object to the controller for processing.
I have now included all the code.
My view:
#model BCMManci.ViewModels.OrderCreateGroup
#{
ViewBag.Title = "Create";
}
<h2>New Order</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<h4>#Html.DisplayFor(model => model.Order.Customer.FullName)</h4>
<table>
<tr>
<td><b>Order Date:</b> #Html.DisplayFor(model => model.Order.OrderDate)</td>
<td><b>Status:</b> #Html.DisplayFor(model => model.Order.OrderStatus.OrderStatusName)</td>
</tr>
<tr>
<td colspan="2">
<b>Notes</b>
#Html.EditorFor(model => model.Order.Notes, new { htmlAttributes = new { #class = "form-control" } })
</td>
</tr>
</table>
#Html.ValidationMessageFor(model => model.Order.Notes, "", new { #class = "text-danger" })
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<table class="table table-striped table-hover">
<thead>
<tr>
<td>Name</td>
<td>Price</td>
<td>Discount</td>
<td>Total</td>
<td>Quantity</td>
</tr>
</thead>
<tbody>
#foreach (var product in Model.ProductWithPrices)
{
<tr>
<td>
#Html.DisplayFor(modelItem => product.ProductName)
</td>
<td>
#Html.DisplayFor(modelItem => product.SellingPrice)
</td>
<td>
#Html.DisplayFor(modelItem => product.DiscountPrice)
</td>
<td>
#Html.DisplayFor(modelItem => product.TotalPrice)
</td>
<td>
#Html.EditorFor(modelItem => product.Quantity, new { htmlAttributes = new { #class = "form-control" } })
</td>
</tr>
}
</tbody>
</table>
<input type="submit" value="Create" class="btn btn-default" />
}
<div class="btn btn-danger">
#Html.ActionLink("Cancel", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Order,ProductWithPrices,Order.Note,product.Quantity")] OrderCreateGroup order)
{
try
{
if (ModelState.IsValid)
{
db.Orders.Add(order.Order);
foreach (var orderItem in order.ProductWithPrices.Select(item => new OrderItem
{
OrderId = order.Order.OrderId,
ProductId = item.ProductId,
Quantity = item.Quantity,
ItemPrice = item.SellingPrice,
ItemDiscount = item.DiscountPrice,
ItemTotal = item.TotalPrice
}))
{
db.OrderItems.Add(orderItem);
}
db.SaveChanges();
return RedirectToAction("ConfirmOrder", new {id = order.Order.OrderId});
}
}
catch (DataException /* dex */)
{
//TODO: Log the error (uncomment dex variable name and add a line here to write a log.
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
ViewBag.Products = db.Products.Where(model => model.IsActive == true);
PopulateDropdownLists();
return View(order);
}
Data Source:
public class OrderCreateGroup
{
public OrderCreateGroup()
{
ProductWithPrices = new List<ProductWithPrice>();
}
public Order Order { get; set; }
public ICollection<ProductWithPrice> ProductWithPrices { get; set; }
}
public class ProductWithPrice : Product
{
public decimal SellingPrice { get; set; }
public decimal DiscountPrice { get; set; }
public int Quantity { get; set; }
public decimal TotalPrice { get; set; }
}
However, the values that are entered on the form are not being passed, through. So I can't access them in the controller. The 'productWithPrices' collection is null although there is Data in it on the web page.
I have tried making it asyc and also tried changing the ActionLink button like below but it didn't get to the controller.
#Html.ActionLink("Create", "Create", "Orders", new { orderCreateGoup = Model }, null)
This is the controller but it now doesn't make sense as the parameter passed in the datasource for the page.
public ActionResult Create(OrderCreateGroup orderCreateGoup)
Please, can you give me direction on the best way of doing this?
In your OrderCreateGroup class initialize the collection to an empty list.
public class OrderCreateGroup
{
public OrderCreateGroup()
{
ProductWithPrices = new List<ProductWithPrice>();
}
public Order Order { get; set; }
public ICollection<ProductWithPrice> ProductWithPrices { get; set; }
}
You'll need to add #Html.HiddenFor(m => m.SellingPrice) and similarly for other bound fields that are using DisplayFor if you want to post them back to the controller.
Note: For your benefit, try to have a look at the generated HTML code when your page is rendered in the browser and see what tags are generated inside the <form> tag with a name attribute.
make sure you bind the appropriate property from the complex object, like the following:
#model BCMManci.ViewModels.OrderCreateGroup
...
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
...
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OrderCreateGroup.Order.Quantity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.OrderCreateGroup.Order.Quantity, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Note:model.OrderCreateGroup.Order.Quantity would be one the your order's property.
hope this helps.

Multiple Buttons not binding in MVC. Return nulls once form submitted

I am trying to create this MVC form for data capturing. In one of the requirement we need to capture value from multiple Radio buttons. I am able to display multiple radio buttons on view but not able to capture selected value once form is submitted.
Here is the screenshot:
Second Tab
Here is Model
public class DemoModel
{
[Required]
[StringLength(150, ErrorMessage = "Name cannot be longer than 150 characters.")]
[Display(Name = "Name")]
public string Name { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email")]
public string Email { get; set; }
public List<LocationDetail> Locations { get; set; }
}
public class LocationDetail
{
public string LocatioName { get; set; }
public string LocatioDesc{ get; set; }
public List<Position> Positions { get; set; }
}
public class Position
{
public string ID { get; set; }
public string Type { get; set; }
}
Here is Controller
public ActionResult Contact()
{
DemoModel model = new DemoModel();
model.Name = "Enter your name here";
model.Email = "Enter your email here";
model.Locations = GetLocations();
return View(model);
}
List<LocationDetail> GetLocations()
{
List<Position> itms = new List<Position>{
new Position{ID="1", Type="position1"},
new Position{ID="2", Type="position2"},
new Position{ID="3", Type="position3"},
new Position{ID="4", Type="position4"},
new Position{ID="5", Type="position5"}
};
return new List<LocationDetail>
{
new LocationDetail() { LocatioName="Location Name goes here",LocatioDesc="Location Desc Goes here",Positions=itms}
};
}
[HttpPost]
public ActionResult Contact(DemoModel model)
{
if (ModelState.IsValid)
{
return View("FormSuccess");
}
// Just for testing in order to know when it is the serverside validation that has failed
ModelState.AddModelError("", "Server-side validation failed.");
// If we got this far something failed, redisplay form
return View("Contact", model);
}
Here is View
#using (Html.BeginForm())
{
<div id="wizard" class="swMain">
<ul>
<li>
<a href="#step-1">
<span class="stepDesc"> Personal Details </span>
#*<label class="stepNumber">1</label>
<span class="stepDesc">
Step 1<br />
<small>Step 1 description</small>
</span>*#
</a>
</li>
<li>
<a href="#step-2">
<span class="stepDesc"> Location Details </span>
#*<label class="stepNumber">2</label>
<span class="stepDesc">
Step 2<br />
<small>Step 2 description</small>
</span>*#
</a>
</li>
<li>
<a href="#step-3">
<span class="stepDesc"> Others </span>
#*<label class="stepNumber">3</label>
<span class="stepDesc">
Step 3<br />
<small>Step 3 description</small>
</span>*#
</a>
</li>
</ul>
<div id="step-1">
<h2 class="StepTitle">Step 1 Content</h2>
<!-- step content -->
<table>
<tr>
<td>
#Html.LabelFor(model => model.Name)
</td>
<td>
#Html.EditorFor(model => model.Name)
</td>
<td>
#Html.ValidationMessageFor(model => model.Name)
</td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.Email)
</td>
<td>
#Html.EditorFor(model => model.Email)
</td>
<td>
#Html.ValidationMessageFor(model => model.Email)
</td>
<td>
<input type="submit" value="Create" />
</td>
</tr>
</table>
</div>
<div id="step-2">
<h2 class="StepTitle">Step 2 Content</h2>
<!-- step content -->
<table>
<tr>
<td>
#Html.LabelFor(model => model.Locations[0].LocatioName)
</td>
<td>
#Html.EditorFor(model => model.Locations[0].LocatioName)
</td>
<td></td>
</tr>
<tr>
<td>
#Html.LabelFor(model => model.Locations[0].LocatioDesc)
</td>
<td>
#Html.EditorFor(model => model.Locations[0].LocatioDesc)
<br />
</td>
</tr>
<tr>
<td>
#{
foreach (var itm in Model.Locations[0].Positions)
{
<div>
#Html.RadioButton(itm.Type, new { id = "ID_" + itm.ID })
#Html.Label("Location" + itm.ID, itm.Type)
</div>
}
}
</td>
<td>
#*#for (int i = 0; i < Model.MobileSite[0].MobileHomePageHeroBannerLocation1.Count; i++)
{
#Html.CheckBoxFor(m => m.MobileSite[0].MobileHomePageHeroBannerLocation1[i].Checked, new { id = "Hero" })
#Html.DisplayFor(m => m.MobileSite[0].MobileHomePageHeroBannerLocation1[i].Text)
<br />
}*#
</td>
</tr>
</table>
#*#Html.LabelFor(model => model.MobileSite[0].MobileHomePageHeroBannerLocation[0].Items.Count.ToString())*#
</div>
<div id="step-3">
<h2 class="StepTitle">Step 3 Title</h2>
<!-- step content -->
</div>
</div>
<input type="button" id="wizard-submit" value="Submit" />
}
Following code in view used to create radio buttons
#{
foreach (var itm in Model.Locations[0].Positions)
{
<div>
#Html.RadioButton(itm.Type, new { id = "ID_" + itm.ID })
#Html.Label("Location" + itm.ID, itm.Type)
</div>
}
}
Here is form after submission.
Any comments here please?
Positions passed back as null. I would like to pass all the options and position3 as selected (true)
Cheers
Harry
As per my understanding you will only get selected radio button value when form submit because you are using similar like radiobutton list.
For get that selected radiobutton value you need to define one property in LocationDetail class.
public class LocationDetail
{
public string LocatioName { get; set; }
public string LocatioDesc{ get; set; }
public List<Position> Positions { get; set; }
public int SelectedPosition{get;set;}
}
Now use this property in view like this
#{
foreach (var itm in Model.Locations[0].Positions)
{
<div>
#Html.RadioButtonFor(m=>Model.Locations[0].SelectedPosition,itm.ID ,new { id = "ID_" + itm.ID })
#Html.Label("Location" + itm.ID, itm.Type)
</div>
}
}
Now you should get selected radio button value from model.Location.SelectedPosition.
I think the problem is with the way you are configuring your Position list (the Type is different):
List<Position> itms = new List<Position>{
new Position{ID="1", Type="position1"},
new Position{ID="2", Type="position2"},
new Position{ID="3", Type="position3"},
new Position{ID="4", Type="position4"},
new Position{ID="5", Type="position5"}
};
And on view you are using
<div>
#Html.RadioButton(itm.Type, new { id = "ID_" + itm.ID })
#Html.Label("Location" + itm.ID, itm.Type)
</div>
Once HTML is generated, when the form is posted the values will not not be attached as it do not have a link with model.
You should use RadioButtonFor or even better in your case RadioButtonListFor

EntityFrameWork DataFirst and MVC Default Parameters Are Null

I am working on a project utilizing MVC4 and EF Data First in VS2012. The database has a table with a composite key comprised of two fields. When the edit action is called the optional default parameter id always has the value of zero and not the value of the selected record so nothing is returned from the DB. If the table has a single field primary key the parameter is populated correctly. I am not sure how to fix this, any suggest would help. Thanks
public class GamesController : Controller
{
private Context db = new Context();
//
// GET: /Games/
public ActionResult Index()
{
var gms = from g in db.Games orderby g.Date, g.GameNumber ascending select g;
return View(gms);
// return View(db.Games.ToList());
}
//
// GET: /Games/Edit/5
public ActionResult Edit(int id = 0)
{
Games games = db.Games.Find(id);
if (games == null)
{
return HttpNotFound();
}
return View(games);
}
Adding a second parameter did not work.
public ActionResult Edit(int id = 0, int sid = 0)
{
Games games = db.Games.Find(id, sid);
if (games == null)
{
return HttpNotFound();
}
return View(games);
}
DatabaseTable
[Games]
GameNumber (PK, int not null)
Date (date, not null)
HomeTeamId (FK, int , not null)
AwayTeamId (FK, int , not null)
HomeTeamScore(int, null)
AwayTeamScore(int, null)
FieldId(FK, int, null)
GameType(nvarchar(15), null)
Season_Id(PK, FK, int, not null)
CreateDate(date, null)
RouteConfig.cs
namespace RetryMVC1
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Games",
url: "Games/{action}/{id}&{sid}",
defaults: new { controller = "Games", action = "Index", sid = "", gid = "" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
View
#model RetryMVC1.Models.Games
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Games</legend>
#Html.HiddenFor(model => model.GameNumber)
<div class="editor-label">
#Html.LabelFor(model => model.Date)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Date)
#Html.ValidationMessageFor(model => model.Date)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.HomeTeamId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.HomeTeamId)
#Html.ValidationMessageFor(model => model.HomeTeamId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AwayTeamId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AwayTeamId)
#Html.ValidationMessageFor(model => model.AwayTeamId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.HomeTeamScore)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.HomeTeamScore)
#Html.ValidationMessageFor(model => model.HomeTeamScore)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.AwayTeamScore)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.AwayTeamScore)
#Html.ValidationMessageFor(model => model.AwayTeamScore)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.FieldId)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FieldId)
#Html.ValidationMessageFor(model => model.FieldId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.GameType)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.GameType)
#Html.ValidationMessageFor(model => model.GameType)
</div>
#Html.HiddenFor(model => model.Season_Id)
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
This is the view in question
#model IEnumerable<RetryMVC1.Models.Games>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.Date)
</th>
<th>
#Html.DisplayNameFor(model => model.HomeTeamId)
</th>
<th>
#Html.DisplayNameFor(model => model.AwayTeamId)
</th>
<th>
#Html.DisplayNameFor(model => model.HomeTeamScore)
</th>
<th>
#Html.DisplayNameFor(model => model.AwayTeamScore)
</th>
<th>
#Html.DisplayNameFor(model => model.FieldId)
</th>
<th>
#Html.DisplayNameFor(model => model.GameType)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
<td>
#Html.DisplayFor(modelItem => item.HomeTeamId)
</td>
<td>
#Html.DisplayFor(modelItem => item.AwayTeamId)
</td>
<td>
#Html.DisplayFor(modelItem => item.HomeTeamScore)
</td>
<td>
#Html.DisplayFor(modelItem => item.AwayTeamScore)
</td>
<td>
#Html.DisplayFor(modelItem => item.FieldId)
</td>
<td>
#Html.DisplayFor(modelItem => item.GameType)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
You need to add the second parameter to your route config.

Categories

Resources