Can not call string depending of Id linq lambda expression - c#

I want to call my StudentName depending of Id selected that I use in selectlist to use in a bootstrap alert after post action, but I can not get it.
ViewModel:
public class StudentsViewModel
{
public String StudentName { get; set; }//ForeignKey
public int StudentId { get; set; }//ForeignKey
public int SelectedStudent { get; set; }
public IEnumerable<SelectListItem> Student{ get; set; }
}
}
Get Controller:
public ActionResult Create(Students model)
{
var student= db.StudentsList.Select(x => x.StudentName).ToList();
var vm = new StudentsViewModel
{
Student= new SelectList(db.StudentList, "StudentId", "StudentName"),
StudentName = student.ToString()
};
POST CONTROLLER:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(StudentsViewModel model)
{
var student =
db.StudentsList.Where(x => x.StudentId == model.SelectedStudent)
.Select(x => x.StudentName)
.FirstOrDefault();
try
{
if (ModelState.IsValid)
{
var student=
db.StudentsList.Where(x => x.StudentId == model.SelectedStudent)
.Select(x => x.StudentName)
.FirstOrDefault();
var studs= new Students
{
StudentId = model.SelectedStudent,
StudentName = student
};
db.StudentsList.Add(studs);
db.SaveChanges();
Success(string.Format("Register of" + student + "has been created"),true);
return RedirectToAction("Index", "Students");
}
}
catch (Exception)
{
Danger(string.Format("Cannot create your register"), true);
}
return View(model);
}
Index Students View(Where I want to display my bootstrap alert)
#model IEnumerable<xxx.Models.Student>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Student.StudentName)
</th>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Student.StudentName)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.StudentId }) |
#Html.ActionLink("Details", "Details", new { id=item.StudentId }) |
#Html.ActionLink("Delete", "Delete", new { id=item.StudentId })
</td>
</tr>
}
</table>
Create View:
#model xxx.Models.ViewModels.StudentViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Students</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-10">
#Html.DropDownListFor(m => m.SelectedStudent, Model.Student, "-Select an option-", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.SelectedStudent)
</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>
So my consult is
var student= db.StudentsList.Where(x => x.StudentId == model.SelectedStudent).Select(x => x.StudentName).FirstOrDefault();
But in my call StudentName = student I put a breakpoint and always come null.
Thankyou in advance

Related

How can I view both table and form in same view

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

MVC Passing a Complex Object to the controller for saving

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

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

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.

ASP.NET MVC4 IEnumerable empty on post

I have read several answers on this issue but despite this, it would appear I have developed code blindness.
I have the following view model:
public class IndividualProductVm
{
public virtual Products Products { get; set; }
public ProductSummary ProductSummary { get; set; }
public virtual IEnumerable<ProductSimpleResponse> ProductSimpleResponse { get; set; }
}
This is then passed into a view and then a partial view:
#model Websites.ViewModels.IndividualProductVm #{ ViewBag.Title = "Edit"; }
<h2>Edit</h2>
#using (Html.BeginForm(null, null, FormMethod.Post, new { name = "form", id = "mainForm" })) { #Html.AntiForgeryToken() #Html.ValidationSummary(true, "", new { #class = "text-danger" }) #Html.HiddenFor(model => model.Products.Id) #Html.HiddenFor(model
=> model.ProductSummary.SupplierId) Html.RenderPartial("_IndividualProduct", Model);
<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>
#Html.ActionLink("Back to List", "Index", new { id = Model.ProductSummary.SupplierId }, new { #class = "btn btn-default" })
</div>
#section Scripts { #Scripts.Render("~/bundles/jqueryval") }
#model Websites.ViewModels.IndividualProductVm
<div>
#Html.LabelFor(model => model.Products.ProductCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div>
#Html.DisplayFor(model => model.Products.ProductCode, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<div style="clear:both;"></div>
<div>
#Html.LabelFor(model => model.Products.ProductDescription, htmlAttributes: new { #class = "control-label col-md-2" })
<div>
#Html.DisplayFor(model => model.Products.ProductDescription, new { htmlAttributes = new { #class = "form-control" } })
</div>
</div>
<table class="table">
<tr>
<th>
Present
</th>
</tr>
#foreach (var item in Model.ProductSimpleResponse)
{
<tr>
#Html.HiddenFor(modelItem => item.Id)
#Html.HiddenFor(modelItem => item.SupplierId)
#Html.HiddenFor(modelItem => item.ProductCode)
<td>
#Html.EditorFor(modelItem => item.Present)
</td>
</tr>
}
</table>
However, when I enter the edit post, my viewmodel is null for the IEnumerable<ProductSimpleResponse> but fine for the other two classes.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(IndividualProductVm model)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index", new { id = model.ProductSummary.SupplierId });
}
return View(model.Products);
}
If someone can explain what I'm doing wrong, I'd be most grateful.
Your property name is ProductSimpleResponse, alhtough the type is ProductSvhcSimpleResponse, so to iterate through it you should have.
#foreach (var item in Model.ProductSimpleResponse)
NOT
#foreach (var item in Model.ProductSvhcSimpleResponse)
use List because
IEnumerable is suitable just for iterate through collection and you can not modify (Add or Remove) data IEnumerable bring ALL data from server to client then filter them, assume that you have a lot of records so IEnumerable puts overhead on your memory.
public class IndividualProductVm
{
public virtual Products Products { get; set; }
public ProductSummary ProductSummary { get; set; }
public virtual List<ProductSvhcSimpleResponse> ProductSimpleResponse { get; set; }
}
More help click here

How to perform edit function in MVC4 without using entity framework?

I just want to edit my old data using mvc4. For eg, the city name needs to be changed from chennai
(dropdownlist which is populated from model) to pune. Can anyone guide me pls?
Below is my code:
Controller:
[HttpGet]
public ActionResult display(Create model)
{
List<Create> city = new List<Create>();
using (connectionstring pcs = new connectionstring())
{
city = pcs.grp.OrderBy(a => a.cityname).ToList();
}
ViewBag.cityname = new SelectList(city, "cityname", "cityname");
return View(model);
}
[HttpPost, ActionName("display")]
[ValidateAntiForgeryToken]
public ActionResult display1( Create cg)
{
List<Create> city = new List<Create>();
using (connectionstring pcs = new connectionstring())
{
city = pcs.grp.OrderBy(a => a.cityname).ToList();
}
ViewBag.cityname = new SelectList(city, "cityname", "cityname");
if (ModelState.IsValid)
{
string oldgcityname = cg.cityname.ToString().Trim();
using (NpgsqlConnection conn = new NpgsqlConnection(ConfigurationManager.ConnectionStrings["portalconnectionstring"].ConnectionString))
{
using( NpgsqlCommand cmd=new NpgsqlCommand("update tblcity set cityname='$1' where cityname='"+oldcityname+"'",conn))
cmd.ExecuteNonQuery();
}
}
return View(cg);
}
View:
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
#Html.AntiForgeryToken()
<table>
<tr> <td>
<div class="editor-label">
#Html.Label("Select old cityname")
</div> </td>
<td>
<div class="editor-field">
#Html.DropDownListFor(model => model.cityname,#ViewBag.cityname as SelectList,"select")
#Html.ValidationMessageFor(model => model.cityname)
</div>
</td></tr>
<tr> <td>
<div class="editor-label">
#Html.Label("Enter new cityname")
</div> </td>
<td>
<div class="editor-field">
#Html.EditorFor(model => model.cityname)
#Html.ValidationMessageFor(model => model.cityname)
</div>
</td></tr>
<tr><td>
<p>
<input type="submit" value="Create" />
</p>
</td></tr>
Create a view model that contains properties for the old and new names
View model
public class CreateVM
{
[Display(Name = "Old name")]
[Required]
public string OldName { get; set; }
[Display(Name = "New name")]
[Required]
public string NewName { get; set; }
public SelectList CityList { get; set; }
}
Controller
[HttpGet]
public ActionResult Edit(CreateVM model)
{
CreateVM model = new CreateVM();
...
model.CityList = new SelectList(city, "cityname", "cityname");
return View(model);
}
[HttpPost]
public ActionResult Edit(CreateVM model)
{
// the model now contains the selected old name and its new name
}
View
#model CreateVM
#using(Html.BeginForm())
{
#Html.LabelFor(m => m.OldName)
#Html.DropDownListFor(m => m.OldName, Model.CityList, "-Please select-")
#Html.ValidationMessageFor(m => m.OldName)
#Html.LabelFor(m => m.NewName)
#Html.TextBoxFor(m => m.NewName)
#Html.ValidationMessageFor(m => m.NewName)
<input type="submit" />
}
And as Jon Skeet has noted, use parameterized SQL!

Categories

Resources