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>
Related
I'm new to .net. I have this model that has been a real trouble for me for days.
class DetailedRecordModel
public class DetailedRecordModel
{
public string RecordID { get; set; }
public string EmployeeID { get; set; }
public string CustomerID { get; set; }
[DataType(DataType.Date)]
public string InitDate { get; set; }
[DataType(DataType.Date)]
public string DeliveryDate { get; set; }
public virtual ICollection<PurchaseDetail> detail{ get; set; }
}
class PurchaseDetail
public class PurchaseDetail
{
public string ProductID { get; set; }
public int Qty { get; set; }
public double price { get; set; }
public string RecordID { get; set; }
}
controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(DetailedRecordModel record)
{
if (ModelState.IsValid)
{
return View(record);
}
return RedirectToAction("ViewRecords");
}
html
<div class="form-group">
#Html.LabelFor(model => model.EmployeeID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.EmployeeID, (IEnumerable<SelectListItem>)ViewData["sellistemp"])
#Html.ValidationMessageFor(model => model.EmployeeID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CustomerID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CustomerID, (IEnumerable<SelectListItem>)ViewData["sellistcust"])
#Html.ValidationMessageFor(model => model.CustomerID, "", new { #class = "text-danger" })
</div>
</div>
<tr>
<td style="display:none" id="Index0" name="detail.Index" value="0"></td>
<td>1</td>
<td id="ProductID" name="detail[0].ProductID" value="sp00002">sp00002</td>
<td id="Qty" name="detail[0].Qty" value="12123">12123</td>
<td id="price" name="detail[0].price" value="2312">2312</td>
</tr>
<tr>
<td style="display:none" id="Index1" name="detail.Index" value="1"></td>
<td>2</td>
<td id="ProductID" name="detail[1].ProductID" value="sp00003">sp00003</td>
<td id="Qty" name="detail[1].Qty" value="2323">2323</td>
<td id="price" name="detail[1].price" value="3223">3223</td>
</tr>
for RecordID, EmployeeID, CustomerID, InitDate and DeliveryDate passing them to the controller is all fine, however I always get null for <PurchaseDetail> detail. How can I solve this problem?
you have to pass the model to the view by using View(myModel) or RedirectToAction("ViewRecords", record)
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(DetailedRecordModel record)
{
if (ModelState.IsValid)
{
return RedirectToAction("ViewRecords", record);
}
return View(record);
}
public IActionResult ViewRecords(DetailedRecordModel model)
{
return View(model);
}
then in the View you can access the model like here How to pass model in MVC view
add the definition of your model at the top of #model DetailedRecordModel;
after you added the model you can access it everywhere in your file with #Model (in html) or Model
#model DetailedRecordModel;
#{
ViewData["Title"] = "ViewRecords";
}
<h1>ViewRecords</h1>
<div class="form-group">
#Html.LabelFor(model => model.EmployeeID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.EmployeeID, (IEnumerable<SelectListItem>)ViewData["sellistemp"])
#Html.ValidationMessageFor(model => model.EmployeeID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CustomerID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.CustomerID, (IEnumerable<SelectListItem>)ViewData["sellistcust"])
#Html.ValidationMessageFor(model => model.CustomerID, "", new { #class = "text-danger" })
</div>
</div>
#foreach (var entry in Model.detail)
{
<tr>
<td style="display:none" id="Index0" name="detail.Index" value="0"></td>
<td>1</td>
<td id="ProductID" name="#entry.ProductID" value="sp00002">sp00002</td>
<td id="Qty" name="#entry.Qty" value="12123">12123</td>
<td id="price" name="#entry.price" value="2312">2312</td>
</tr>
}
After 2 wretching days of desperation I know that in order to bind the values, I found the answer by declaring an object DetailedRecordModel inside model PurchaseDetail and I have to change the name of each <input> tag into detail[index].somevariable
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>();
}
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 */ })
Please don't argue me too hard, I'm just a beginner in asp.net
I have made controllers/views based on this model http://tinypic.com/view.php?pic=awq14w&s=8#.VG2Q4PmUdUV
When I create a new Survey I have this view http://tinypic.com/view.php?pic=33ayubs&s=8#.VG2R6fmUdUV
How can I modify the view in order to get this form type when I create/view/edit:
Questions | Answers | Comments
------------------------------
Q1 | TextBox | TextBox
Q2 | TextBox | TextBox
Q3 | TextBox | TextBox
Controller :
public class SurveysController : Controller
{
private OrganizationASEMEntities1 db = new OrganizationASEMEntities1();
// GET: Surveys
public ActionResult Index()
{
var surveys = db.Surveys.Include(s => s.Question).Include(s => s.User);
return View(surveys.ToList());
}
// GET: Surveys/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Survey survey = db.Surveys.Find(id);
if (survey == null)
{
return HttpNotFound();
}
return View(survey);
}
// GET: Surveys/Create
public ActionResult Create()
{
ViewBag.QuestionId = new SelectList(db.Questions, "QuestionId", "QuestionText");
ViewBag.UserId = new SelectList(db.Users, "UserId", "Name");
return View();
}
// POST: Surveys/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "SurveyId,UserId,QuestionId,Answer,Comment")] Survey survey)
{
if (ModelState.IsValid)
{
db.Surveys.Add(survey);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.QuestionId = new SelectList(db.Questions, "QuestionId", "QuestionText", survey.QuestionId);
ViewBag.UserId = new SelectList(db.Users, "UserId", "Name", survey.UserId);
return View(survey);
}
// GET: Surveys/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Survey survey = db.Surveys.Find(id);
if (survey == null)
{
return HttpNotFound();
}
ViewBag.QuestionId = new SelectList(db.Questions, "QuestionId", "QuestionText", survey.QuestionId);
ViewBag.UserId = new SelectList(db.Users, "UserId", "Name", survey.UserId);
return View(survey);
}
// POST: Surveys/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "SurveyId,UserId,QuestionId,Answer,Comment")] Survey survey)
{
if (ModelState.IsValid)
{
db.Entry(survey).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.QuestionId = new SelectList(db.Questions, "QuestionId", "QuestionText", survey.QuestionId);
ViewBag.UserId = new SelectList(db.Users, "UserId", "Name", survey.UserId);
return View(survey);
}
// GET: Surveys/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Survey survey = db.Surveys.Find(id);
if (survey == null)
{
return HttpNotFound();
}
return View(survey);
}
// POST: Surveys/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Survey survey = db.Surveys.Find(id);
db.Surveys.Remove(survey);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
View Create:
#model OrganizationASEM.Models.Survey
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Survey</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.UserId, "UserId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("UserId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.UserId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.QuestionId, "QuestionId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("QuestionId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.QuestionId, "", new { #class = "text-danger" })
</div>
</div>
enter code here
<div class="form-group">
#Html.LabelFor(model => model.Answer, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Answer, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Answer, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Comment, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Comment, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Comment, "", 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>
View Edit:
#model OrganizationASEM.Models.Survey
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Survey</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.SurveyId)
<div class="form-group">
#Html.LabelFor(model => model.UserId, "UserId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("UserId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.UserId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.QuestionId, "QuestionId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("QuestionId", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.QuestionId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Answer, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Answer, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Answer, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Comment, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Comment, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Comment, "", 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>
View Index:
#model IEnumerable<OrganizationASEM.Models.Survey>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Answer)
</th>
<th>
#Html.DisplayNameFor(model => model.Comment)
</th>
<th>
#Html.DisplayNameFor(model => model.Question.QuestionText)
</th>
<th>
#Html.DisplayNameFor(model => model.User.Name)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Answer)
</td>
<td>
#Html.DisplayFor(modelItem => item.Comment)
</td>
<td>
#Html.DisplayFor(modelItem => item.Question.QuestionText)
</td>
<td>
#Html.DisplayFor(modelItem => item.User.Name)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.SurveyId }) |
#Html.ActionLink("Details", "Details", new { id=item.SurveyId }) |
#Html.ActionLink("Delete", "Delete", new { id=item.SurveyId })
</td>
</tr>
}
</table>
If you want to have all fieds in a single row you have to switch from:
<div class="form-horizontal">
to:
<div class="form-inline">
see here:
http://getbootstrap.com/css/#forms
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.