C# - MVC 4 Many-To-Many Checkboxes values passed to another view - c#

I have been working on this and have been searching for hours and still can not figure out a solution.
I am trying to display the ItemNames of the checked checkboxes from my AsoociateMenuItems view to my Index view. Would appreciate any help I can get.
MenuItemViewModel:
public class MenuItemViewModel
{
public int MenuId { get; set; }
public double ItemPrice { get; set; }
public string ItemName { get; set; }
public bool Selected { get; set; }
public virtual ICollection<IngredientViewModel> Ingredients { get; set;}
}
OrderViewModel:
public class OrderViewModel
{
public int OrderId { get; set; }
public int TableNum { get; set; }
public string Notes { get; set; }
public double Discount { get; set; }
public virtual ICollection<MenuItemViewModel> MenuItem { get; set; }
}
Index:
#model IEnumerable<Final_POS.Models.Order>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Employee.EmpName)
</th>
<th>
#Html.DisplayNameFor(model => model.TableNum)
</th>
<th>
+
#Html.DisplayNameFor(model => model.Discount)
</th>
<th>
#Html.DisplayNameFor(model => model.MenuItems)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Employee.EmpName)
</td>
<td>
#Html.DisplayFor(modelItem => item.TableNum)
</td>
<td>
#Html.DisplayFor(modelItem => item.Discount)
</td>
<td>
#Html.EditorFor(modelItem => item.MenuItems)
</td>
<td>
#Html.ActionLink("Edit", "AsoociateMenuItems", new { id=item.OrderId }) |
#Html.ActionLink("Details", "Details", new { id=item.OrderId }) |
#Html.ActionLink("Delete", "Delete", new { id=item.OrderId })
</td>
</tr>
}
</table>
AsoociateMenuItems:
-this is a replacement for my edit view
#model Final_POS.Models.ViewModel.OrderViewModel
#{
ViewBag.Title = "AsoociateMenuItems";
}
<h2>AsoociateMenuItems</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>OrderViewModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.OrderId, new { htmlAttributes = new { #class = "form-control" } })
<div class="form-group">
#Html.LabelFor(model => model.TableNum, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TableNum, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TableNum, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.HiddenFor(model => model.Notes, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.HiddenFor(model => model.Notes, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Notes, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Discount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Discount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Discount, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EmployeeEmpId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EmployeeEmpId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EmployeeEmpId, "", new { #class = "text-danger" })
</div>
</div>
#Html.EditorFor(model => model.MenuItem)
<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 next code snippet is being used by my AsoociateMenuItems in this line #Html.EditorFor(model => model.MenuItem)
MenuItemViewModel: (View)
#model Final_POS.Models.ViewModel.MenuItemViewModel
<fieldset>
#Html.HiddenFor(model => model.MenuId)
#Html.CheckBoxFor(model => model.Selected)
#Html.DisplayFor(model => model.ItemName)
#Html.DisplayFor(model => model.ItemPrice)
</fieldset>
Controller:
public class OrdersController : Controller
{
private POSContext db = new POSContext();
// GET: Orders
public ActionResult Index()
{
var orders = db.Orders.Include(o => o.Employee);
return View(orders.ToList());
}
// GET: Orders/Details/5
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Order order = db.Orders.Find(id);
if (order == null)
{
return HttpNotFound();
}
return View(order);
}
// GET: Orders/Create
public ActionResult Create()
{
ViewBag.EmployeeEmpId = new SelectList(db.Employees, "EmpId", "EmpName");
return View();
}
// POST: Orders/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 = "OrderId,TableNum,Discount,EmployeeEmpId")] Order order)
{
if (ModelState.IsValid)
{
db.Orders.Add(order);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.EmployeeEmpId = new SelectList(db.Employees, "EmpId", "EmpName", order.EmployeeEmpId);
return View(order);
}
// GET: Orders/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Order order = db.Orders.Find(id);
if (order == null)
{
return HttpNotFound();
}
ViewBag.EmployeeEmpId = new SelectList(db.Employees, "EmpId", "EmpName", order.EmployeeEmpId);
return View(order);
}
// POST: Orders/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 = "OrderId,TableNum,Discount,EmployeeEmpId")] Order order)
{
if (ModelState.IsValid)
{
db.Entry(order).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.EmployeeEmpId = new SelectList(db.Employees, "EmpId", "EmpName", order.EmployeeEmpId);
return View(order);
}
// GET: Orders/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Order order = db.Orders.Find(id);
if (order == null)
{
return HttpNotFound();
}
return View(order);
}
// POST: Orders/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Order order = db.Orders.Find(id);
db.Orders.Remove(order);
db.SaveChanges();
return RedirectToAction("Index");
}
public ActionResult AsoociateMenuItems(int? id)
{
Order _order = db.Orders.Find(id);
if (_order == null)
{
return HttpNotFound();
}
OrderViewModel _orderViewModel = new OrderViewModel()
{
OrderId = _order.OrderId,
Discount = _order.Discount,
TableNum = _order.TableNum,
EmployeeEmpId = _order.EmployeeEmpId
};
List<MenuItemViewModel> _menuItemViewModel = new List<MenuItemViewModel>();
foreach (MenuItem menuItem in db.MenuItems)
{
_menuItemViewModel.Add(new MenuItemViewModel()
{
MenuId = menuItem.MenuId,
ItemName = menuItem.ItemName,
ItemPrice = menuItem.ItemPrice,
Selected = _order.MenuItems.Contains(menuItem)
});
}
_orderViewModel.MenuItem = _menuItemViewModel;
return View(_orderViewModel);
}
[HttpPost]
public ActionResult AsoociateMenuItems(OrderViewModel _orderViewModel)
{
Order _order = db.Orders.Find(_orderViewModel.OrderId);
_order.MenuItems.Clear();
foreach (MenuItemViewModel _menuItemViewModel in _orderViewModel.MenuItem)
{
if (_menuItemViewModel.Selected)
{
MenuItem _menuItem = db.MenuItems.Find(_menuItemViewModel.MenuId);
_order.MenuItems.Add(_menuItem);
}
}
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}

Let's start.
Your question is really hard for understanding. BUT I hope that I understood.
At first, you should use model in all views. It is really important. You MUST do it. The easiest way - just extend you OrderViewModel with EmpName
public class OrderViewModel
{
public int OrderId { get; set; }
public int TableNum { get; set; }
public string Notes { get; set; }
public double Discount { get; set; }
public string EmpName { get; set; }
public virtual ICollection<MenuItemViewModel> MenuItems { get; set; } //renamed to plural
}
Than change your Index View
#model IEnumerable<OrderViewModel>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.EmpName)
</th>
<th>
#Html.DisplayNameFor(model => model.TableNum)
</th>
<th>
#Html.DisplayNameFor(model => model.Discount)
</th>
<th>
#Html.DisplayNameFor(model => model.MenuItems)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.EmpName)
</td>
<td>
#Html.DisplayFor(modelItem => item.TableNum)
</td>
<td>
#Html.DisplayFor(modelItem => item.Discount)
</td>
<td>
#Html.EditorFor(modelItem => item.MenuItems)
</td>
<td>
#Html.ActionLink("Edit", "AsoociateMenuItems", new { id=item.OrderId }) |
#Html.ActionLink("Details", "Details", new { id=item.OrderId }) |
#Html.ActionLink("Delete", "Delete", new { id=item.OrderId })
</td>
</tr>
}
</table>
Than change the controller method Index (Just get menuitems from db also)
// GET: Orders
public ActionResult Index()
{
var orders = db.Orders.Include(o => o.Employee).Include(o => o.MenuItems);
var orderModels = new List<OrderViewModel>();
foreach(var _order in orders)
{
OrderViewModel _orderViewModel = new OrderViewModel()
{
OrderId = _order.OrderId,
Discount = _order.Discount,
TableNum = _order.TableNum,
EmpName = _order.Employee.EmpName
};
List<MenuItemViewModel> _menuItemViewModels = new List<MenuItemViewModel>();
foreach (MenuItem menuItem in order.MenuItems)
{
if(_order.MenuItems.Contains(menuItem)) //where selected is true
{
_menuItemViewModel.Add(new MenuItemViewModel()
{
MenuId = menuItem.MenuId,
ItemName = menuItem.ItemName,
ItemPrice = menuItem.ItemPrice,
});
}
}
_orderViewModel.MenuItems = _menuItemViewModels;
orderModels.Add(_orderViewModel);
}
return View(orderModels);
}
I hope you will understand what I meant. And sure, my code need code refactoring, but you can do it by yourself.

Related

Pass id of parent view to child view and use it in controller - ASP.NET MVC 5

I am having a problem sending parent ID to child ID, even if I do, I want to display the child's data only of a particular parent. In my code, List is the parent, and Notes are the children. When I create a List, I have redirected to Notes Index Page (Different Controller) along with ID but in all lists, I can see the same notes. I am using TempData in NotesController to keep hold of that ID.
List Controller:
//Index
public ActionResult Index()
{
return View(db.Lists.ToList());
}
//Create
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(ListViewModel lists)
{
if (ModelState.IsValid)
{
Lists list = new Lists();
list.CreationDate = DateTime.Now;
list.ListName = lists.ListName;
db.Lists.Add(list);
db.SaveChanges();
int? idFromView = list.Id;
return RedirectToAction("Index", "NotesInLists", new { id = idFromView });
}
return View(lists);
}
Notes Controller:
//Index
public ActionResult Index(int? id)
{
TempData["idFromView"] = id;
return View(db.NotesInLists.ToList());
}
//Create
public ActionResult CreateWithtext()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateWithtext(NoteTagViewModel notesInList)
{
if (ModelState.IsValid)
{
List<string> TagsList = notesInList.TagsList.Split(',').ToList();
NotesInList note = new NotesInList();
int tempDataId = (int)TempData["idFromView"];
note.CreationDate = DateTime.Now;
note.ListName = notesInList.ListName;
note.TextDescription = notesInList.TextDescription;
note.listID = tempDataId;
db.NotesInLists.Add(note);
db.SaveChanges();
//saving tags
foreach (var item in TagsList)
{
Tags tag = new Tags();
tag.CreationDate = DateTime.Now;
tag.TagName = item;
tag.Note_Id = note.Id;
db.Tags.Add(tag);
}
db.SaveChanges();
return RedirectToAction("Index", new { id = tempDataId });
}
return View(notesInList);
}
Here, in this NotesController, I am also saving tags and it is working fine, but the main issue is with List. Also using ViewModels but that is of no concern to me for now. If I try accessing List using
Lists list = new List();
I still am not able to check and compare that ID with that List ID, it throws an exception.
List Model:
namespace NoteBlocks.Models
{
public class Lists
{
public int Id { get; set; }
[Required]
[Display(Name = "List Name")]
public string ListName { get; set; }
[Display(Name = "Creation Date")]
public DateTime? CreationDate { get; set; }
[Display(Name = "Last Updated")]
public DateTime? UpdateDate { get; set; }
}
}
List ViewModel:
namespace NoteBlocks.ViewModels
{
public class ListViewModel
{
public int Id { get; set; }
[Required]
[Display(Name = "List Name")]
public string ListName { get; set; }
[Display(Name = "Creation Date")]
public DateTime? CreationDate { get; set; }
[Display(Name = "Last Updated")]
public DateTime? UpdateDate { get; set; }
}
}
Notes Model:
namespace NoteBlocks.Models
{
public class NotesInList
{
public int Id { get; set; }
[Required]
[Display(Name = "List Name")]
public string ListName { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Creation Date")]
public DateTime? CreationDate { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Last Updated")]
public DateTime? UpdateDate { get; set; }
public string customFile { get; set; }
[Display(Name = "Enter Note Content")]
public string TextDescription { get; set; }
public Lists List { get; set; }
public int listID { get; set; }
}
}
Notes ViewModel:
namespace NoteBlocks.Models
{
public class NoteTagViewModel
{
public int NoteId { get; set; }
[Required]
[Display(Name = "List Name")]
public string ListName { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Creation Date")]
public DateTime? CreationDate { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Last Updated")]
public DateTime? UpdateDate { get; set; }
public string customFile { get; set; }
[Display(Name = "Enter Note Content")]
public string TextDescription { get; set; }
//multiple tags
public string TagsList { get; set; }
public Lists List { get; set; }
public int ListId { get; set; }
}
}
Created a foreign key but it is not working.
HTML - List Index
#model IEnumerable<NoteBlocks.Models.Lists>
#{
ViewBag.Title = "List";
//ViewBag.Id = model.Lists.Id;
}
<h2>List</h2>
<p>
#Html.ActionLink(" Create New List", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.ListName)
</th>
<th>
#Html.DisplayNameFor(model => model.CreationDate)
</th>
<th>
#Html.DisplayNameFor(model => model.UpdateDate)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
//using ActionLink to open list of notes for that particular List
//and passing particular List ID from here if already created
#Html.ActionLink(item.ListName, "Index", "NotesInLists", new { id = item.Id }, null)
#*#TempData.Peek("tempDataId")*#
</td>
<td>
#Html.DisplayFor(modelItem => item.CreationDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.UpdateDate)
</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>
HTML - List Create
#model NoteBlocks.Models.Lists
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>List</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ListName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ListName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ListName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreationDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CreationDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CreationDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UpdateDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UpdateDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UpdateDate, "", 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>
HTML - Notes Index
#model IEnumerable<NoteBlocks.Models.NotesInList>
#{
ViewBag.Title = "List Notes";
}
<h2>List Notes</h2>
<p id="buttonsInPTag">
<button type="button" class="btn btn-primary" id="addButton1"><span class="glyphicon glyphicon-plus">#Html.ActionLink(" Create Textual Note", "CreateWithtext")</span></button>
<button type="button" class="btn btn-primary" id="addButton2"><span class="glyphicon glyphicon-plus">#Html.ActionLink(" Create Note from Document", "CreateWithDoc")</span></button>
<button type="button" class="btn btn-primary" id="addButton3"><span class="glyphicon glyphicon-plus">#Html.ActionLink(" Create Image Note", "CreateWithImage")</span></button>
<button type="button" class="btn btn-primary" id="addButton4"><span class="glyphicon glyphicon-plus">#Html.ActionLink(" Create Audio / Video Note", "CreateWithMedia")</span></button>
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.ListName)
</th>
<th>
#Html.DisplayNameFor(model => model.CreationDate)
</th>
<th>
#Html.DisplayNameFor(model => model.UpdateDate)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ListName)
</td>
<td>
#Html.DisplayFor(modelItem => item.CreationDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.UpdateDate)
</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>
HTML - Notes CreateWithText
#model NoteBlocks.Models.NoteTagViewModel
#{
ViewBag.Title = "Create Note with Text";
}
<h2>Create Note with Text</h2>
#using (Html.BeginForm("CreateWithText", "NotesInLists", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ListName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ListName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ListName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TextDescription, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<textarea cols="50" rows="12" class=form-control id="TextDescription" name="TextDescription"></textarea>
#Html.ValidationMessageFor(model => model.TextDescription, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Tags", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="text" id="tagsField" name="tagsField" class=form-control data-role="tagsinput" />
<input type="hidden" name="TagsList" id="TagsList" />
</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>
#section scripts
{
<script>
$(document.body).on('focusout', '.bootstrap-tagsinput input', () => {
let array = $('#tagsField').tagsinput('items');
$("#TagsList").val(array);
})
</script>
}
I am stuck to this point. Please guide. p.s. using code first approach.
There is no filter applied to the query that gets notes in your Index action of notes controller.
I think adding where method;
.Where(x=>x.listID == id)
will solve your problem.
//Index
public ActionResult Index(int? id)
{
TempData["idFromView"] = id;
return View(db.NotesInLists/*.Where(x=>x.listID == id)*/.ToList());
}

How to Insert a record in database using dropdownlist In asp.net mvc?

I m implement a drop-down list with entity framework database first approach in asp.net MVC??
I implement a drop-down list in MVC and when I M debugging In watch Window My Inserted Record Is display but Not Inserted In Database that is an issue??
DatabaseField Name:
tbl_product
ProductID int
ProductName varchar(50)
ProductList varchar(50)
tbl_product.cs
// <auto-generated>
// </auto-generated>
public partial class tbl_product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public string ProductList { get; set; }
public IEnumerable<SelectListItem> ProductLists { get; set; }
}
HomeController.cs
ProductEntities prodb = new ProductEntities();
public ActionResult Index()
{
return View(prodb.tbl_product.ToList());
}
public ActionResult Prodlist()
{
var ProductLists = GetallProductList();
var model = new tbl_product();
model.ProductLists = GetSelectListItems(ProductLists);
return View(model);
}
[HttpPost]
public ActionResult Prodlist(tbl_product product)
{
var ProductLists = GetallProductList();
product.ProductLists = GetSelectListItems(ProductLists);
if (ModelState.IsValid)
{
prodb.tbl_product.Add(product);
return RedirectToAction("Index");
}
return View("Prodlist", product);
}
private IEnumerable<SelectListItem> GetSelectListItems(IEnumerable<string> elements)
{
var selectList = new List<SelectListItem>();
foreach (var element in elements)
{
selectList.Add(new SelectListItem
{
Value = element,
Text = element
});
}
return selectList;
}
private IEnumerable<string> GetallProductList()
{
return new List<string>
{
"FRIDGE",
"WASHING MACHINE",
"A.C",
};
}
}
view:
Prodlist.cshtml
<div class="form-group">
#Html.LabelFor(model => model.ProductName, htmlAttributes: new { #class = "control-label col-md-2" })
<div>
#Html.EditorFor(model => model.ProductName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductName, "", new { #class = "text-danger" })
</div>
</div>
//product list
<div class="form-group">
#Html.LabelFor(model => model.ProductList, htmlAttributes: new { #class = "control-label col-md-2" })
<div>
#Html.DropDownListFor(model => model.ProductList,Model.ProductLists,"Please Select Your Products:", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductList, "", new { #class = "text-danger" })
</div>
</div>
Model1.Context.cs
// <auto-generated>
// </auto-generated>
public partial class ProductEntities : DbContext
{
public ProductEntities()
: base("name=ProductEntities")
{
}
public virtual DbSet<tbl_product> tbl_product { get; set; }
}
Index.cshtml
#model IEnumerable<DropdownInsertMvc.Models.tbl_product>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.ProductName)
</th>
<th>
#Html.DisplayNameFor(model => model.ProductList)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ProductName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ProductList)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ProductID }) |
#Html.ActionLink("Details", "Details", new { id=item.ProductID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ProductID })
</td>
</tr>
}
</table>
When I m Debugging In Watch Window:
ProductList "FRIDGE" string
ProductLists Count = 3 System.Collections.Generic.IEnumerable {System.Collections.Generic.List}
ProductName "Electronics" string
record is not inserted in the database??
You missed prodb.SaveChanges() after prodb.tbl_product.Add(product); in Prodlist method.
for more information about SaveChanges() you can follow this link

Asp.net - Update related data - Get null when submitting

I got stuck on a problem with returning from view to controller with related data, every time I submit my form with related data, the related data becomes null. (OrderRows)
I check the Chorme develop tool and saw that I do post the OrderRows as row.Id but can see them in Visual Studio as an variable
Classes
public class OrderModel
{
[Key]
public int Id { get; set; }
public int OrderID { get; set; }
public List<OrderRow> OrderRows { get; set; }
}
public class OrderRow
{
[Key]
public int Id { get; set; }
public int OrderID { get; set; }
public int OrderRowID { get; set; }
public OrderModel OrderModel { get; set; }
}
Edit Controller (GET)
public ActionResult Edit(int? id)
{
OrderModel orderModel = db.OrderModel.Where(b => b.Id == id).Include(b => b.OrderRows).FirstOrDefault();
return View(orderModel);
}
Delivered controler (Post, is activated when submitting the form)
public ActionResult Delivered(OrderModel orderModel, FormCollection formCollection)
{
//db.Entry(orderModel).State = EntityState.Modified;
//Set state to Delivered
//db.SaveChanges();
return RedirectToAction("Index");
}
Editview
using (Html.BeginForm())
{
#Html.LabelFor(model => model.OrderID): #Html.DisplayFor(model => model.OrderID)
#Html.HiddenFor(model => model.OrderRows)
<div class="row">
#Html.Label("Delivery information")
<br />
#Html.HiddenFor(model => model.Id, new { htmlAttributes = new { #class = "form-control" } })
#Html.DisplayFor(model => model.Id, "", new { #class = "text-danger" })
<br />
#Html.HiddenFor(model => model.OrderID, new { htmlAttributes = new { #class = "form-control" } })
#Html.DisplayFor(model => model.OrderID, "", new { #class = "text-danger" })
<br />
</div>
<table class="table table-striped table-bordered">
#foreach (var row in Model.OrderRows)
{
<tr>
<td>
<input type="checkbox" value="#row.OrderRowID">
</td>
<td>
#Html.HiddenFor(model => row.Id, new { htmlAttributes = new { #class = "form-control" } })
#Html.DisplayFor(model => row.Id, "", new { #class = "text-danger" })
</td>
<td>
#Html.HiddenFor(model => row.OrderID, new { htmlAttributes = new { #class = "form-control" } })
#Html.DisplayFor(model => row.OrderID, "", new { #class = "text-danger" })
</td>
<td>
#Html.HiddenFor(model => row.OrderRowID, new { htmlAttributes = new { #class = "form-control" } })
#Html.DisplayFor(model => row.OrderRowID, "", new { #class = "text-danger" })
</td>
<td>
#Html.HiddenFor(model => row.OrderModel, new { htmlAttributes = new { #class = "form-control" } })
#Html.DisplayFor(model => row.OrderModel, "", new { #class = "text-danger" })
</td>
</tr>
}
</table>
<div class="form-group">
<input type="submit" value="Mark as Delivered" formaction="/OrderModels/Delivered" class="btn btn-info" />
</div>
}
I think what you want is to use OrderRow instead OrderModel. If I understand what you need, you want to get (one) OrderModel and include (many) OrderRows. If that's what you want you should use OrderRow as your model in your view:
OrderRow orderRows = db.OrderRow.Where(b => b.OrderModel.Id == id).ToList();
return View(orderRows );
Then you want to change the model in your view:
#model IEnumberable<OrderRow>
This way, you can have all the OrderRows including its OrderModel
Your controller is defined as public ActionResult Edit(int? id), meaning it expects a value of id, of type int.
You won't get any other data through it, if you want the value from OrderRows you need to either change your form to submit it as id, or update your controller to accept a public ActionResult Edit(int OrderRows).
Either way, you are still also submitting a lot of junk that isn't being picked up by the controller, you need to only submit the values the controller is defined to accept (as above). What you really want to be doing is #html.BeginFrom(viewModelClass)'ing a viewmodel and submitting that to your controller with all the values.
Eg:
Public ActionResult Edit(ViewModel model)
{
var value = model.OrderRows
}

Store update, insert, or delete statement affected an unexpected number of rows (0) ASP.NET MVC Entity Framework

So im building a timesheet application where the user can register timesheets to the database. Iv'e used Entity Framework for the CRUD operations, but I keep getting the error as you see on the title every time im trying to edit a record...
Here's some code:
Model:
namespace Aviato.Models
{
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public partial class TimesheetEntry
{
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int UserId { get; set; }
[Key]
[Column(Order = 1)]
[StringLength(50)]
public string ProjectId { get; set; }
[Key]
[Column(Order = 2, TypeName = "date")]
public DateTime EntryDate { get; set; }
public decimal HoursWorked { get; set; }
public virtual Project Project { get; set; }
public virtual User User { get; set; }
}
}
ViewModel (Dont know if I really need one or not):
namespace Aviato.ViewModel
{
public class TimesheetEntryModel
{
public int UserId { get; set; }
public string ProjectId { get; set; }
public decimal HoursWorked { get; set; }
public string EntryDate { get; set; }
}
}
View (Index):
#model IEnumerable<Aviato.Models.TimesheetEntry>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Tidrapportering</h1>
<p>
#Html.ActionLink("Skapa ny", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.UserId)
</th>
<th>
#Html.DisplayNameFor(model => model.Project.ProjectName)
</th>
<th>
#Html.DisplayNameFor(model => model.EntryDate)
</th>
<th>
#Html.DisplayNameFor(model => model.HoursWorked)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.UserId)
</td>
<td>
#Html.DisplayFor(modelItem => item.Project.ProjectName)
</td>
<td>
#Html.DisplayFor(modelItem => item.EntryDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.HoursWorked)
</td>
<td>
#Html.ActionLink("Redigera", "Edit", new { id=item.UserId, item.ProjectId, item.EntryDate, item.HoursWorked }) |
#Html.ActionLink("Ta bort", "Delete", new { id=item.UserId, item.ProjectId, item.EntryDate, item.HoursWorked })
</td>
</tr>
}
</table>
<div>
#Html.ActionLink("Tillbaka", "Index", "User")
</div>
View: (Edit)
#model Aviato.ViewModel.TimesheetEntryModel
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Redigera</h1>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.UserId)
<div class="form-group">
#Html.LabelFor(model => model.ProjectId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ProjectId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProjectId)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EntryDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EntryDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EntryDate)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HoursWorked, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HoursWorked, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HoursWorked)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Spara" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Tillbaka", "Index")
</div>
Controller:
namespace Aviato.Controllers
{
public class TimesheetEntryController : Controller
{
private readonly AviatoModel _db = new AviatoModel(); //Database Model.
public ActionResult Index()
{
var userId = (int)Session["userId"];
var timesheetentries = _db.TimesheetEntries.Where(t => t.UserId == userId).ToList();
return View(timesheetentries);
}
public ActionResult Edit(int id, string projectId, decimal hoursWorked, string entryDate)
{
var timesheetEntryModel = new TimesheetEntryModel();
timesheetEntryModel.UserId = id;
timesheetEntryModel.ProjectId = projectId;
timesheetEntryModel.EntryDate = entryDate;
timesheetEntryModel.HoursWorked = hoursWorked;
ViewBag.ProjectId = new SelectList(_db.Projects, "ProjectId", "ProjectName", timesheetEntryModel.ProjectId);
ViewBag.UserId = new SelectList(_db.Users, "UserId", "SocialSecurityNumber", timesheetEntryModel.UserId);
return View(timesheetEntryModel);
}
[HttpPost]
public ActionResult Edit(TimesheetEntry timesheetentry)
{
_db.Entry(timesheetentry).State = EntityState.Modified;
_db.SaveChanges();
ViewBag.ProjectId = new SelectList(_db.Projects, "ProjectId", "ProjectName", timesheetentry.ProjectId);
ViewBag.UserId = new SelectList(_db.Users, "UserId", "SocialSecurityNumber", timesheetentry.UserId);
return RedirectToAction("Index");
}
Database:
CREATE TABLE [dbo].[TimesheetEntries] (
[UserId] INT NOT NULL,
[ProjectId] NVARCHAR (50) NOT NULL,
[EntryDate] DATE NOT NULL,
[HoursWorked] DECIMAL (8, 1) CONSTRAINT [DF_TimesheetEntries_HoursWorked] DEFAULT ((0.0)) NOT NULL,
CONSTRAINT [PK_TimesheetEntries] PRIMARY KEY CLUSTERED ([UserId] ASC, [ProjectId] ASC, [EntryDate] ASC),
CONSTRAINT [FK_TimesheetEntries_Users] FOREIGN KEY ([UserId]) REFERENCES [dbo].[Users] ([UserId]),
CONSTRAINT [FK_TimesheetEntries_Projects] FOREIGN KEY ([ProjectId]) REFERENCES [dbo].[Projects] ([ProjectId])
);
database table TimesheetEntry is this autoincrement field public int UserId { get; set; } ,if this not autoincrement please set it in table autocreament i hope this work.

Store update, insert, or delete statement affected an unexpected number of rows (0) Entity Framework

So im building a timesheet application where the user can register timesheets to the database. Iv'e used Entity Framework for the CRUD operations, but I keep getting the error as you see on the title every time im trying to edit a record...
Here's some code:
Model:
namespace Aviato.Models
{
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
public partial class TimesheetEntry
{
[Key]
[Column(Order = 0)]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int UserId { get; set; }
[Key]
[Column(Order = 1)]
[StringLength(50)]
public string ProjectId { get; set; }
[Key]
[Column(Order = 2, TypeName = "date")]
public DateTime EntryDate { get; set; }
public decimal HoursWorked { get; set; }
public virtual Project Project { get; set; }
public virtual User User { get; set; }
}
}
ViewModel (Dont know if I really need one or not):
namespace Aviato.ViewModel
{
public class TimesheetEntryModel
{
public int UserId { get; set; }
public string ProjectId { get; set; }
public decimal HoursWorked { get; set; }
public string EntryDate { get; set; }
}
}
View (Index):
#model IEnumerable<Aviato.Models.TimesheetEntry>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Tidrapportering</h1>
<p>
#Html.ActionLink("Skapa ny", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.UserId)
</th>
<th>
#Html.DisplayNameFor(model => model.Project.ProjectName)
</th>
<th>
#Html.DisplayNameFor(model => model.EntryDate)
</th>
<th>
#Html.DisplayNameFor(model => model.HoursWorked)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.UserId)
</td>
<td>
#Html.DisplayFor(modelItem => item.Project.ProjectName)
</td>
<td>
#Html.DisplayFor(modelItem => item.EntryDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.HoursWorked)
</td>
<td>
#Html.ActionLink("Redigera", "Edit", new { id=item.UserId, item.ProjectId, item.EntryDate, item.HoursWorked }) |
#Html.ActionLink("Ta bort", "Delete", new { id=item.UserId, item.ProjectId, item.EntryDate, item.HoursWorked })
</td>
</tr>
}
</table>
<div>
#Html.ActionLink("Tillbaka", "Index", "User")
</div>
View: (Edit)
#model Aviato.ViewModel.TimesheetEntryModel
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Redigera</h1>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.UserId)
<div class="form-group">
#Html.LabelFor(model => model.ProjectId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ProjectId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProjectId)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.EntryDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.EntryDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.EntryDate)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HoursWorked, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HoursWorked, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HoursWorked)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Spara" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Tillbaka", "Index")
</div>
Controller:
namespace Aviato.Controllers
{
public class TimesheetEntryController : Controller
{
private readonly AviatoModel _db = new AviatoModel(); //Database Model.
public ActionResult Index()
{
var userId = (int)Session["userId"];
var timesheetentries = _db.TimesheetEntries.Where(t => t.UserId == userId).ToList();
return View(timesheetentries);
}
public ActionResult Edit(int id, string projectId, decimal hoursWorked, string entryDate)
{
var timesheetEntryModel = new TimesheetEntryModel();
timesheetEntryModel.UserId = id;
timesheetEntryModel.ProjectId = projectId;
timesheetEntryModel.EntryDate = entryDate;
timesheetEntryModel.HoursWorked = hoursWorked;
ViewBag.ProjectId = new SelectList(_db.Projects, "ProjectId", "ProjectName", timesheetEntryModel.ProjectId);
ViewBag.UserId = new SelectList(_db.Users, "UserId", "SocialSecurityNumber", timesheetEntryModel.UserId);
return View(timesheetEntryModel);
}
[HttpPost]
public ActionResult Edit(TimesheetEntry timesheetentry)
{
_db.Entry(timesheetentry).State = EntityState.Modified;
_db.SaveChanges();
ViewBag.ProjectId = new SelectList(_db.Projects, "ProjectId", "ProjectName", timesheetentry.ProjectId);
ViewBag.UserId = new SelectList(_db.Users, "UserId", "SocialSecurityNumber", timesheetentry.UserId);
return RedirectToAction("Index");
}
Database:
CREATE TABLE [dbo].[TimesheetEntries] (
[UserId] INT NOT NULL,
[ProjectId] NVARCHAR (50) NOT NULL,
[EntryDate] DATE NOT NULL,
[HoursWorked] DECIMAL (8, 1) CONSTRAINT [DF_TimesheetEntries_HoursWorked] DEFAULT ((0.0)) NOT NULL,
CONSTRAINT [PK_TimesheetEntries] PRIMARY KEY CLUSTERED ([UserId] ASC, [ProjectId] ASC, [EntryDate] ASC),
CONSTRAINT [FK_TimesheetEntries_Users] FOREIGN KEY ([UserId]) REFERENCES [dbo].[Users] ([UserId]),
CONSTRAINT [FK_TimesheetEntries_Projects] FOREIGN KEY ([ProjectId]) REFERENCES [dbo].[Projects] ([ProjectId])
);
I don't think you can pass the UserId to Edit action, you can directly pass the TimesheetEntryModel to the Edit action.

Categories

Resources