EntityFrameWork DataFirst and MVC Default Parameters Are Null - c#

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.

Related

How do i add a student to the attendance table

I want to add students to the Attendance Table through the Class_Schedule controller. To do this I created an public ActionResult:
public ActionResult Register(int? id)
{
if (id == null)
{
return RedirectToAction("Index");
}
Class_Schedule class_Schedule = db.Class_Schedule.Find(id);
if (class_Schedule == null)
{
return RedirectToAction("Index");
}
//This is the collects the class_schedule ID to make the attendance specific for each class ViewBag.CSid = id;
ViewBag.studentID = new SelectList(db.Students, "StudentID", "Full_Name");
ViewBag.instructorID = new SelectList(db.Instructors, "InstructorID", "Name");
var attendances = db.Attendances;
return View(attendances.ToList());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register([Bind(Include = "AttendanceID,csID,InstructorID,StudentID")] Attendance attendance)
{
try
{
if (ModelState.IsValid)
{
db.Attendances.Add(attendance);
db.SaveChanges();
//ViewBag.msg = "Instructor Added";
return RedirectToAction("Register");
}
return View(attendance);
}
catch
{
return View(attendance);
}
}
This is my view:
#model IEnumerable<BBM.Models.Attendance>
#{
ViewBag.Title = "Register";
}
<h2>Class Schedule #ViewBag.CSid</h2>
#using (Html.BeginForm("Register","Class_Schedule", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-group">
#{
var studentid = Model.Select(model => model.StudentID.ToString());
}
#Html.Label("StudentID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("StudentID", null, htmlAttributes: new { #class = "form-control" })
</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>
<h4>Student register</h4>
<table class="table">
<tr>
<th>
Attendance ID
</th>
<th>
Student ID
</th>
<th>
Student Name
</th>
<th>
Expiry Date
</th>
</tr>
#if (Model != null)
{
foreach (var item in Model.Where(p => p.csID.Equals(ViewBag.csID)))
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.AttendanceID)
</td>
<td>
#Html.DisplayFor(modelItem => item.StudentID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Student.Full_Name)
</td>
<td>
#if (item.Student.Payments != null && item.Student.Payments.Any(p => p.Expires > DateTime.Now))
{
#Html.DisplayFor(modelItem => item.Student.Payments.OrderByDescending(p => p.paymentID).First(p => p.Expires > DateTime.Now).Expires)
}
else
{
#Html.DisplayName("Expired");
}
</td>
</tr>
}
}
</table>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
This view has a select list to select the students you want to add but but the student ID isn't going into the parameter and the postMethod isn't happening
The ones that are already in there are for test purposes and i did them through the sql server
You have only a specified drop-down id and html attribute. you forgot to pass data to the drop-down helper as you fill in the ViewBag. Update as below for student
#Html.DropDownList("StudentID",htmlAttributes:new { #class = "control-label col-md-2" },selectList:new SelectList(ViewBag.studentID))
Please check that you getting studentId on the post method.

form not passing values to action method [duplicate]

This question already has answers here:
Post an HTML Table to ADO.NET DataTable
(2 answers)
Closed 5 years ago.
I am trying to call Action method "Createdirect" on form submission from Index.cshtml view.
I want to list and create in the same view. Code works for list..it displays data, but when trying to create, it does not pass form data to action method.. It passes null values as shown in screenshot attached..
Index.cshtml
#using CRUD_Entity_DataFirst.Models
#model Tuple<Customer_MVC,IEnumerable<Customer_MVC>>
#{
ViewBag.Title = "Index";
}
<h4>Customers</h4>
<link href="#Url.Content("~/Content/table.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-1.10.2.min.js")"></script>
<script src="#Url.Content("~/Scripts/select.js")"></script>
<script src="#Url.Content("~/Scripts/table.js")"></script>
#Html.DropDownList("searchby", new SelectList(Enum.GetValues(typeof(search))), "- - Search By - -")
<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search ..">
<label id="bdy" style="color:red"></label>
<table class="table" id="myTable">
<tr>
<th>
#Html.DisplayNameFor(model => model.Item1.First_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1.Last_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1.Email)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1.Mobile)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1.Address_Temp)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1.Address_Perm)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1.State)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1.City)
</th>
<th>
#Html.DisplayNameFor(model => model.Item1.Zipcode)
</th>
<th></th>
</tr>
#foreach (var item in Model.Item2)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.First_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Last_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
<td>
#Html.DisplayFor(modelItem => item.Mobile)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address_Temp)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address_Perm)
</td>
<td>
#Html.DisplayFor(modelItem => item.State)
</td>
<td>
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
#Html.DisplayFor(modelItem => item.Zipcode)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("View", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id }, new { onclick = "return confirm('Are you sure wants to delete?');" })
</td>
</tr>
}
</table>
#using (Html.BeginForm("Createdirect","Customer",FormMethod.Post))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.EditorFor(model => model.Item1.First_Name, new { htmlAttributes = new { #class = "form-control", #style = "width:80px" } })
#Html.ValidationMessageFor(model => model.Item1.First_Name, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.EditorFor(model => model.Item1.Last_Name, new { htmlAttributes = new { #class = "form-control", #style = "width:80px" } })
#Html.ValidationMessageFor(model => model.Item1.Last_Name, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.EditorFor(model => model.Item1.Email, new { htmlAttributes = new { #class = "form-control", #style = "width:80px" } })
#Html.ValidationMessageFor(model => model.Item1.Email, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.EditorFor(model => model.Item1.Mobile, new { htmlAttributes = new { #class = "form-control", #style = "width:80px" } })
#Html.ValidationMessageFor(model => model.Item1.Mobile, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.EditorFor(model => model.Item1.Address_Temp, new { htmlAttributes = new { #class = "form-control", #style = "width:80px" } })
#Html.ValidationMessageFor(model => model.Item1.Address_Temp, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.EditorFor(model => model.Item1.Address_Perm, new { htmlAttributes = new { #class = "form-control", #style = "width:80px" } })
#Html.ValidationMessageFor(model => model.Item1.Address_Perm, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.DropDownListFor(model => model.Item1.State, new SelectList(Enum.GetValues(typeof(States))), "State", new { #class = "form-control", #style = "width:80px" })
#Html.ValidationMessageFor(model => model.Item1.State, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.DropDownListFor(model => model.Item1.City, new SelectList(Enum.GetValues(typeof(Cities))), "City", new { #class = "form-control", #style = "width:80px" })
#Html.ValidationMessageFor(model => model.Item1.City, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.EditorFor(model => model.Item1.Zipcode, new { htmlAttributes = new { #class = "form-control", #style = "width:80px" } })
#Html.ValidationMessageFor(model => model.Item1.Zipcode, "", new { #class = "text-danger" })
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
}
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
CustomerController.cs
// GET: Customer
public ActionResult Index()
{
if (Session["User"] == null)
{
return RedirectToAction("Login");
}
return View(Tuple.Create<Customer_MVC,IEnumerable<Customer_MVC>>(new Customer_MVC(),vd.Customer_MVC.ToList()));
}
//create:post
[HttpPost]
public ActionResult Createdirect(Customer_MVC custcreate)
{
if (ModelState.IsValid)
{
vd.Customer_MVC.Add(custcreate);
vd.SaveChanges();
return RedirectToAction("Index");
}
return View(custcreate);
}
Customer_MVC.cs
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace CRUD_Entity_DataFirst.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
[MetadataType(typeof(CustomersValid))]
public partial class Customer_MVC
{
public int Id { get; set; }
public string First_Name { get; set; }
public string Last_Name { get; set; }
public string Email { get; set; }
public string Mobile { get; set; }
public string Address_Temp { get; set; }
public string Address_Perm { get; set; }
public string City { get; set; }
public string State { get; set; }
public Nullable<int> Zipcode { get; set; }
}
}
here it showing null values
Model binding does not work when you use a foreach loop as the html controls are not rendered with meaningful IDs.
Change your loop to a for loop:
#for (int i = 0; i < Model.Item2.Length; i++)
{
<tr>
<td>
#Html.DisplayFor(model => model.Item2[i].First_Name)
</td>
<td>
...
You may also have an issue (but try it first) as the IEnumerable is not an instance at the point of binding. If this is the case then the only solution would be to change your Tuple based model to a class implementation:
public class MyModel
{
public Customer_MVC Item1 { get; set; }
public IEnumerable<Customer_MVC> Item2 { get; set; } = new List<Customer_MVC>();
}

I need to apply update and delete in asp.net MVC 4

Basically i have created a mvc application that will be performing CRUD operations on the database data using entity framework generated from database edmx.So in this after adding EDM and configuring database settings i've added a controller named CRUD with scaffolding enabled to read/write action views and attached model and DB conttext to it.Now everything works as desired upto the point of adding new employee ie Create.The problem comes when i run the index page of crud controller and in which when i press the actionlink edit or delete for any specific employee data it doesn't find that Edit and Delete cshtml pages at all and instead shows the error 404 resource not found.Please help me figure out what's wrong,i'm posting my whole code below:
public class CRUDController : Controller
{
private TestDBEntities2 db = new TestDBEntities2();
public ActionResult Index()
{
return View(db.Emps.ToList());
}
public ActionResult Details(int id = 0)
{
Emp emp = db.Emps.Find(id);
if (emp == null)
{
return HttpNotFound();
}
return View(emp);
}
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Emp emp)
{
if (ModelState.IsValid)
{
db.Emps.Add(emp);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(emp);
}
public ActionResult Edit(int id = 0)
{
Emp emp = db.Emps.Find(id);
if (emp == null)
{
return HttpNotFound();
}
return View(emp);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(Emp emp)
{
if (ModelState.IsValid)
{
db.Entry(emp).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(emp);
}
public ActionResult Delete(int id = 0)
{
Emp emp = db.Emps.Find(id);
if (emp == null)
{
return HttpNotFound();
}
return View(emp);
}
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Emp emp = db.Emps.Find(id);
db.Emps.Remove(emp);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
Index.cshtml
#model IEnumerable<MvcApplication2.Emp>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.EmployeeID)
</th>
<th>
#Html.DisplayNameFor(model => model.Firstname)
</th>
<th>
#Html.DisplayNameFor(model => model.Lastname)
</th>
<th>
#Html.DisplayNameFor(model => model.Age)
</th>
<th>
#Html.DisplayNameFor(model => model.Project)
</th>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.EmployeeID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Firstname)
</td>
<td>
#Html.DisplayFor(modelItem => item.Lastname)
</td>
<td>
#Html.DisplayFor(modelItem => item.Age)
</td>
<td>
#Html.DisplayFor(modelItem => item.Project)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</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>
Create.cshtml
#model MvcApplication2.Emp
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Emp</legend>
<div class="editor-label">
#Html.LabelFor(model => model.EmployeeID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.EmployeeID)
#Html.ValidationMessageFor(model => model.EmployeeID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Firstname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Firstname)
#Html.ValidationMessageFor(model => model.Firstname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Lastname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Lastname)
#Html.ValidationMessageFor(model => model.Lastname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Age)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Age)
#Html.ValidationMessageFor(model => model.Age)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Project)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Project)
#Html.ValidationMessageFor(model => model.Project)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Address)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Address)
#Html.ValidationMessageFor(model => model.Address)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Edit.cshtml
#model MvcApplication2.Emp
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Emp</legend>
<div class="editor-label">
#Html.LabelFor(model => model.EmployeeID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.EmployeeID)
#Html.ValidationMessageFor(model => model.EmployeeID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Firstname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Firstname)
#Html.ValidationMessageFor(model => model.Firstname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Lastname)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Lastname)
#Html.ValidationMessageFor(model => model.Lastname)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Age)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Age)
#Html.ValidationMessageFor(model => model.Age)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Project)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Project)
#Html.ValidationMessageFor(model => model.Project)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Address)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Address)
#Html.ValidationMessageFor(model => model.Address)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Image of Solution Explorer:
pass EmployeeID in your ActionLinks:
#Html.ActionLink("Edit", "Edit", new {id=item.EmployeeID }) |
#Html.ActionLink("Details", "Details", new {id=item.EmployeeID }) |
#Html.ActionLink("Delete", "Delete", new {id=item.EmployeeID })
try to add the Controller Name
#Html.ActionLink("Edit", "Edit", "CRUD", new {/*id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", "CRUD", new { /*id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", "CRUD", new { /*id=item.PrimaryKey */ })

No action occurred when clicking on Edite button

i'm trying to edit a row (my project is a simple phone book)from my index view which shows all of my records (Contact) but when i click on the edit button nothing happens
this is my delete method
#region [- Delete -]
#region [- Get -]
[HttpGet]
// [HttpDelete]
public ActionResult Delete(int? _id, Models.EF_Model.Phone_book _model)
{
return View();
}
#endregion
#region [- Post -]
[HttpPost]
//[HttpDelete]
public ActionResult Delete(Models.EF_Model.Phone_book _Model)
{
if (ModelState.IsValid)
{
Ref_ViewModel = new ViewModel.ViewModel();
Ref_ViewModel.Delete(_Model.Id);
}
else
{
ViewBag.Massage = "Choose a Contact";
}
return View(_Model);
}
#endregion
#endregion
this is my edit method in my Home controller
[HttpGet]
public ActionResult Edit(int? _id)
{
if (_id==null)
{
return new HttpStatusCodeResult(HttpStatusCode.NoContent);
}
else
{
Ref_ViewModel = new ViewModel.ViewModel();
return View(Ref_ViewModel.Select(_id));
}
}
[HttpPost]
public ActionResult Edit(ViewModel.DTO.Contact Ref_Contact)
{
if (ModelState.IsValid)
{
Ref_ViewModel = new ViewModel.ViewModel();
Ref_ViewModel.Edit(Ref_Contact, Ref_Contact.Id);
}
else
{
ViewBag.Message = "Choose a Contact";
}
return View();
}
this is it's view(Contact class is a simple DTO class)
#model Phone_Book.ViewModel.DTO.Contact
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Contact</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.FName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Num, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Num, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Num, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
this is my index view
#model IEnumerable<Phone_Book.Models.EF_Model.Phone_book>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.First_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Last_Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Number)
</th>
<th>
#Html.DisplayNameFor(model => model.Email)
</th>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.First_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Last_Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Number)
</td>
<td>
#Html.DisplayFor(modelItem => item.Email)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.Id }) |
#Html.ActionLink("Details", "Details", new { id=item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id=item.Id })
</td>
</tr>
}
</table>
In your Edit method in your HomeController, try this:
[HttpGet]
public ActionResult Edit(int? _id)
{
if (_id==null)
{
return new HttpStatusCodeResult(HttpStatusCode.NoContent);
}
else
{
return View();
}
}
From your Home/Index View make a link to edit action of your HomeController
Index.cshtml
#model IEnumerable<Phone_Book.ViewModel.DTO.Contact>
<h1>Welcome!</h1>
#{
ViewBag.Title = "Home";
}
<table>
<thead>
<tr>
<th>Num</th>
<th>FirstName</th>
<th>LastName</th>
<th>Email</th>
<th>Address</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
#foreach (var contact in Model)
{
<tr>
<td>#contact.Num</td>
<td>#contact.FName</td>
<td>#contact.LName</td>
<td>#contact.Address</td>
<td>#Html.ActionLink("Edit", "Edit", new {id = contact.Id}) </td>
</tr>
}
</tbody>
</table>

Validation for unique username not working in ASP.NET MVC4

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.

Categories

Resources