Posted model is null - asp.net-mvc

I'm not sure what's wrong since I'm very new with MVC. This is a shopping cart. The customer is able to review their cart and edit quantity.
On the HttpPost ViewCart method, the cart is always empty, and number of lines is zero.
Controller:
public ActionResult ViewCart() {
var cart = (CartViewModel)Session["Cart"];
return View(cart);
}
[HttpPost]
public ActionResult ViewCart(CartViewModel cart) {
Session["Cart"] = cart;
return RedirectToAction("Order", "Checkout");
}
View:
#model CartViewModel
using (Html.BeginForm()) {
<h2>Your cart</h2>
<table>
<thead> ... </thead>
<tbody>
#foreach (var item in Model.Lines) {
<tr>
<td>#Html.DisplayFor(modelItem => item.Article.Description)</td>
<td>#Html.EditorFor(modelItem => item.Quantity)</td>
</tr>
}
</tbody>
</table>
<input type="submit" value="Checkout">
}
ViewModel:
public class CartViewModel {
public List<Line> Lines { get; set; }
public CartViewModel() {
Lines = new List<Line>();
}
}

Try changing the view to use indexes:
#model CartViewModel
using (Html.BeginForm()) {
<h2>Your cart</h2>
<table>
<thead> ... </thead>
<tbody>
#for (int i = 0; i < Model.Lines.Count; i++) {
<tr>
<td>#Html.DisplayFor(m => Model.Lines[i].Article.Description) #Html.HiddenFor(m => Model.Lines[i].Article.Id)</td>
<td>#Html.EditorFor(m => Model.Lines[i].Quantity)</td>
</tr>
}
</tbody>
</table>
<input type="submit" value="Checkout">
}

Related

ASP.NET MVC CheckBox List sending always null

I want to create a table with items and checkboxes to select these items. I am including these checkboxes in a list but this list is always returning null. Thank you very much for your help.
Controller:
public ActionResult Index()
{
var expenseTypesView = new ViewExpenseTypesAndSelection
{
ExpensesTypes = _context.ExpenseType.ToList(),
};
return View(expenseTypesView);
}
[HttpPost]
public ActionResult SelectExpensesTypes( ViewExpenseTypesAndSelection SelectedExpenses)
{
var entry = new userSpecificExpenses();
var i = 0;
foreach (var item in SelectedExpenses.SelectedExpenses)
{
if(item)
{
entry.expenseTypeId = i;
entry.UtilisateurId= User.Identity.GetUserId();
_context.UserspecificExpenses.Add(entry);
_context.SaveChanges();
}
i++;
}
return View();
}
View:
#model MBT.ViewModels.ViewExpenseTypesAndSelection
....
#using (Html.BeginForm("SelectExpensesTypes", "ExpenseTypes"))
{
<table class="table table-bordered table-hover">
<thead>
<tr>
<th class="text-center">Expense</th>
<th class="text-center">Include</th>
</tr>
</thead>
<tbody>
#{
for (int i = 0; i < Model.ExpensesTypes.Count; i++)
{
<tr>
<td>
<div class="checkbox">
#Model.ExpensesTypes[i].Type
</div>
</td>
<td>
<div class="checkbox">
#Html.CheckBoxFor(m => m.SelectedExpenses[i])
</div>
</td>
</tr>
}
}
</tbody>
</table>
<button type="submit" class="btn btn-primary">Submit</button>
}
You sending ViewExpenseTypesAndSelection almost null just with ExpensesTypes and then post it back to your post method. It means you send null and receive null.
So what is wrong with that?

how to get selected checkbox in asp.net using entity framework

i'm new to asp.net mvc.I have a list of checkboxes and i want when the checkboxes are selected a new list of selected checkboxs are shown.
my code Product.cs code:
public class Product
{
public int ProductID { get; set; }
public string ProductName { get; set; }
public int Price { get; set; }
public bool Checked { get; set; }
public virtual ICollection<Purchase> Purchases { get; set; }
}
My view:
<h2>Product Lists</h2>
#using (Html.BeginForm())
{
<table class="table">
<tr>
<th>
Product ID
</th>
<th>
Product Name
</th>
<th>
Price
</th>
<th></th>
</tr>
#for (var i = 0; i < Model.Count(); i++)
{
<tr>
<td>
#Html.DisplayFor(x => x[i].ProductID)
</td>
<td>
#Html.DisplayFor(x => x[i].ProductName)
</td>
<td>
#Html.DisplayFor(x => x[i].Price)
</td>
<td>
#Html.CheckBoxFor(x => x[i].Checked, new { Style = "vertical-align:3px}" })
</td>
</tr>
}
</table>
<input type="submit" value="Purchase" class="btn btn-default" />
}
This is my Controller code.I want when the check boxes are selected in a new page the selected check boxes are shown.
my ActionResult:
public ActionResult Index()
{
return View(db.Products.ToList());
}
[HttpPost]
public ActionResult Index(List<Product> list)
{
return View(list);
}
#using (Html.BeginForm())
{
<table class="table">
<tr>
<th>
Product ID
</th>
<th>
Product Name
</th>
<th>
Price
</th>
<th></th>
</tr>
#for (var i = 0; i < Model.Count(); i++)
{
<tr>
<td>
#Html.DisplayFor(x => x[i].ProductID)
</td>
<td>
#Html.DisplayFor(x => x[i].ProductName)
</td>
<td>
#Html.DisplayFor(x => x[i].Price)
</td>
<td>
#Html.CheckBoxFor(x => x[i].Checked, new { Style = "vertical-align:3px}" })
</td>
</tr>
}
</table>
If you already have a List with all checked/unchecked properties and just want to show the checked records in a new view, you can store your list in a TempData and redirect to an action which will use your list:
public ActionResult Index()
{
return View(db.Products.ToList());
}
[HttpPost]
public ActionResult Index(List<Product> list)
{
TempData["CheckedRecords"] = list.Where(x=>x.Checked).ToList(); //Don't forget to add 'using System.Linq;'!
return RedirectToAction("MyOtherView");
}
public ActionResult MyOtherView()
{
var checkedRecords = (List<Product>)TempData["CheckedRecords"];
return View(checkedRecords);
}

save all tr elements of a table with checkbox and send it to the controller , in MVC 4

I am new to MVC and now stuck in a serious problem. it is for me, very serious
I need to load a view with a list of meetings (which is loading fine) in html , I have added a checkbox to each row also. Now I need to save to the database ,only the checked values. But the controller is returning null when posting.. Really stuck and cant find a solution.
Pls see code below which I have done
Model
public class aMeet
{
public List<AcceptedRecords> amList { get; set; }
public static List<AcceptedRecords> GetamList()
{
DataSet ds = new DataSet();
List<AcceptedRecords> resultlist = new List<AcceptedRecords>();
using (cmd)
{
cmd.CommandText = #"SELECT Line_code,person_code,person_address from tbl where meeting_code =859489;
ds = cmd.ExecuteDataSet();
}
if (!Utils.IsDataSetEmpty(ds))
{
AcceptedRecords tpmApp;
foreach (DataRow row in ds.Tables[0].Rows)
{
tpmApp = new AcceptedRecords();
tpmApp = tpmApp.LoadRecords(row);
resultlist.Add(tpmApp);
}
}
return resultlist;
}
}
Model
public class AcceptedRecords
{
public int line_Code { get; set; }
public string person_Name { get; set; }
public string person_Address { get; set; }
public bool extra_checked { get; set; }
}
View
#model projct.Models.aRecs
#using (Html.BeginForm("AddRecord","Home"))
{
<table id="tbl" style ="width:100%" cellpadding="0" cellspacing="0" class="race-fields">
<thead>
<tr>
<th style="width:500px">line code</th>
<th style="width:100px">name</th>
<th style="width:500px">address</th>
<th style="width:500px">extra</th>
</tr>
</thead>
<tbody>
<tr>
#for (int i = 0; i < Model.amList.Count; i++)
{
<tr class="EvenRow">
<td>
#Html.DisplayFor(m => m.amList[i].line_Code) </td>
<td>#Html.DisplayFor(m => m.amList[i].person_name) </td>
<td>#Html.DisplayFor(m => m.amList[i].person_address) </td>
<td>
#Html.CheckBoxFor(m => m.amList[i].extra_checked) </td>
</tr>
}
</tr>
<tr>
<span>
<input type="submit" Value ="Save"/>
</span>
</tr>
</tbody>
</table>
}
Controller
[HttpPost]
public ActionResult AddRecord(List<aMeet> spm)
{
if (spm == null)
throw new ApplicationException("No Parameters passed to Create");
int? appID = 0;
return Json(appID);
}
}
--- It Is triggering to controller on Save but model [spm] is null.
How to get this corrected. Here I need to save to database the tr elements that are checked. Please request any help. I have tried a lot of things but the model is always null/
Many thanks
Assuming your aRecs class has a amList property which is a list of AcceptedRecords
public class aRecs
{
public List<AcceptedRecords> amList { set; get; }
}
Assuming line_code value is a unique (may be primary key) to get a record from your corresponding table, In your view, you need to keep the line_code property value of each item in amList in a hidden field so that when the form is submitted you will get this value and using that you can query the corresponding record and update it.
#model YourNamespaceHere.aRecs
#using (Html.BeginForm("AddRecord","Home"))
{
<table>
#for (int i = 0; i < Model.amList.Count; i++)
{
<tr class="EvenRow">
<td>
#Html.DisplayFor(m => m.amList[i].line_Code)
</td>
<td>#Html.DisplayFor(m => m.amList[i].person_Name) </td>
<td>
#Html.CheckBoxFor(m=>m.amList[i].extra_checked)
#Html.HiddenFor(m => m.amList[i].line_Code)
</td>
</tr>
}
</table>
<input type="submit"/>
}
And in your HttpPost action, your parameter will be a single object of aRecs
[HttpPost]
public ActionResult AddRecord(aRecs model)
{
foreach (var item in model.amList)
{
var lineCode = item.line_Code;
var isChecked = item.extra_checked;
/// get the record using lineCode and update the record.
}
return RedirectToAction("Index");
}

Passing entire Model from a View back to the Controller

I got a list of:
public class Items
{
public String Nro_Item { get; set; }
public Sucursal Sucursal { get; set; }
public Areas Area { get; set; }
public Sectores Sector { get; set; }
public bool ID_Estado { get; set; }
}
I'm passing it to this view:
#using ClientDependency.Core.Mvc
#model IEnumerable<TrackingOperaciones.Controllers.Items>
#{
ViewBag.Title = "Ver Items";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<br/>
#using (Html.BeginForm("CargarRecibidos", "Recepcion", FormMethod.Post))
{
<table class="table table-striped table-bordered table-condensed">
<tr>
<th>
Numero
</th>
<th>
Sucursal
</th>
<th>
Area
</th>
<th>
Sector
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Nro_Item)
</td>
<td>
#Html.DisplayFor(modelItem => item.Sucursal.descripcion)
</td>
<td>
#Html.DisplayFor(modelItem => item.Area.descripcion)
</td>
<td>
#Html.DisplayFor(modelItem => item.Sector.Descripcion)
</td>
<td>
#Html.CheckBoxFor(modelItem => item.ID_Estado)
</td>
</tr>
}
</table>
<p>
<input class="btn" name="Guardar" type="submit" value="Guardar"/> |
#Html.ActionLink("Volver al listado de RecepciĆ³n", "Index")
</p>
}
Until there everything is fine: Now the problem is getting back the entire model with the checked values in a controller for processing it like this one:
[HttpPost]
public ActionResult CargarRecibidos(IEnumerable<Items> items)
{
if (ModelState.IsValid)
{
//do something here
}
return RedirectToAction("Index");
}
}
But i'm falling miserably because "items" came back empty in the postback
i'm guess something is wrong with the form
#using (Html.BeginForm("CargarRecibidos", "Recepcion"))
{
<input class="btn" name="Guardar" type="submit" value="Guardar"/>
}
please help me!
Use IEnumerable
Then the controller input parameter will be List
Perhaps also consider using AJAX POST with JSON objects in place of a form submit (more modern/elegant) but submits are fine too.
Part of the problem is it won't post the entire model since only the checkbox is a form value. I think you need to add an additional hidden value in your form to track the item number and then handle the checkbox values specially in the controller. The item number is appended to "checkbox" in the posted values to keep them distinct.
<tr>
<td>
#Html.DisplayFor(modelItem => item.Nro_Item)
#Html.Hidden("Nro_Item", item.Nro_Item)
</td>
<td>
#Html.DisplayFor(modelItem => item.Sucursal.descripcion)
</td>
<td>
#Html.DisplayFor(modelItem => item.Area.descripcion)
</td>
<td>
#Html.DisplayFor(modelItem => item.Sector.Descripcion)
</td>
<td>
#Html.CheckBox("checkbox" + item.Nro_Item, item.ID_Estado)
</td>
</tr>
In the controller only bind to the number item so it can be used to process the checkboxes:
[HttpPost]
public ActionResult CargarRecibidos(List<string> nro_item)
{
foreach (string item in nro_item)
{
var checkbox=Request.Form["checkbox" + item];
if (checkbox != "false") // if not false then true,false is returned
{
// Do the action for true...
}
else
{
// Do the action for false
}
}
return View();
}

Use properties of different models in view (.net MVC)

I am learning MVC and display a list of products in a view.
#model IEnumerable<Domain.Model.Product>
<table>
<tr>
<th style="width:50px; text-align:left">Id</th>
<th style="text-align:left">Name</th>
<th style="text-align:left">Category</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Category.Name)
</td>
</tr>
}
</table>
The products belong to categories, which are displayed in the right column. I now want to filter the products by categories, for which I would like to use a dropdownlist control. I found #Html.DropDownListFor(), but as far as I understand, this will only give me properties of the currently underlying model (Product).
My controller:
public class ProductController : Controller
{
ProductRepository pr = new ProductRepository();
public ActionResult Default()
{
List<Product> products = pr.GetAll();
return View("List", products);
}
}
You could do something like this. Just create a class with the info that you need.
public class ProductsModel
{
public ProductsModel() {
products = new List<Product>();
categories = new List<SelectListItem>();
}
public List<Product> products { get;set; }
public List<SelectListItem> categories { get;set; }
public int CategoryID { get;set; }
}
Then your controller:
public class ProductController : Controller
{
ProductRepository pr = new ProductRepository();
public ActionResult Default()
{
ProductsModel model = new ProductsModel();
model.products = pr.getAll();
List<Category> categories = pr.getCategories();
model.categories = (from c in categories select new SelectListItem {
Text = c.Name,
Value = c.CategoryID
}).ToList();
return View("List", model);
}
}
Finally, your view
#model IEnumerable<Domain.Model.ProductsModel>
#Html.DropDownListFor(m => model.CategoryID, model.categories)
<table>
<tr>
<th style="width:50px; text-align:left">Id</th>
<th style="text-align:left">Name</th>
<th style="text-align:left">Category</th>
</tr>
#foreach (var item in Model.products) {
<tr>
<td>
#item.Id
</td>
<td>
#item.Name
</td>
<td>
#item.Category.Name
</td>
</tr>
}
</table>

Resources