How to show deserialized TempData object in view? - c#

I'm getting System.NullReferenceException: 'Object reference not set to an instance of an object.' error in Index2.cshtml file after deserializing my TempData object. How can I show my object without getting this error? ( This is my first time asking in here sorry if I made mistakes.)
var products = new List<Products>
{
new Products {Id=56, ProductName="x",Quantity=45},
new Products {Id=55, ProductName="y",Quantity=5},
new Products {Id=54, ProductName="z",Quantity=4},
new Products {Id=53, ProductName="t",Quantity=8},
new Products {Id=52, ProductName="k",Quantity=12}
};
string data = JsonSerializer.Serialize(products);
TempData["products"] = data;
return RedirectToAction("Index2");
public IActionResult Index2()
{
var data = TempData["products"].ToString();
List<Products> products = JsonSerializer.Deserialize<List<Products>>(data);
return View();
}
**Index2.cshtml**
<ul>
#foreach(var item in TempData["products"] as List<Products>)
{
<li>#item.ProductName</li>
}
</ul>

Change your code from:
List<Products> products = JsonSerializer.Deserialize<List<Products>>(data);
To:
TempData["products"] = JsonSerializer.Deserialize<List<Products>>(data);
Or you can use return View(products) to use the data:
public IActionResult Index2()
{
var data = TempData["products"].ToString();
List<Products> products = JsonSerializer.Deserialize<List<Products>>(data);
return View(products);
}
View:
#model List<Products>
<ul>
#foreach (var item in Model)
{
<li>#item.ProductName</li>
}
</ul>

Related

Cannot pass a list from the controller to view

I'm trying to pass a list of values from the controller to the view, but apparently I got this issue where the list cannot be passed. I already tried passing one value and it has no problem. But when I try to pass list, it show the following error -
The model item passed into the dictionary is of type
'System.Collections.Generic.List`1[vidly.Models.pelanggan]', but this
dictionary requires a model item of type 'vidly.models.pelanggan'.
I have this model -
public class pelanggan
{
public string Nama { get; set; }
}
The controller code -
// GET: Pelanggan
public ActionResult Index()
{
var name = new List<pelanggan> {
new pelanggan {Nama = "Paidi" },
new pelanggan {Nama = "Budi" }
};
return View(name);
}
This is my view file
#model vidly.Models.pelanggan
#{
ViewBag.Title = "index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Customer</h2>
#foreach(var Nama in Model.pelanggan)
{
<li>#Nama.Nama</li>
}
I already tried to create a ViewModel but it also showing same error. Can you point where the error is?
You are returning a List<T> from the controller. So, the model declared in your view should be able to receive a list and iterate over it.
Replace the model declaration in the view file with following -
#using vidly.Models;
#model IEnumerable<pelanggan>
Then you can iterate/loop over the model like -
#foreach(var p in Model) // p represents a "pelanggan" object in the list
{
<li>#p.Nama</li>
}
The problem is the missmatch of types between what you return return View(name); and what te view expects #model vidly.Models.pelanggan You could change to #model List<vidly.Models.pelanggan> but instead I'd say:
public class pelanggan
{
public List<string> Namas { get; set; }
}
Then
public ActionResult Index()
{
var model = new pelanggan {
name = new List<string> {
"Paidi",
"Budi"
}
};
return View(model);
}
And finally in your view
#foreach(var Nama in Model.Namas)
{
<li>#Nama</li>
}

Display a list from controller in the view MVC

enter image description hereI have a controller that gets its data from a user defined function using Entity framwework.I am trying to just display my data in the view and populate my table.
My Controller looks like this:
public ActionResult Index()
{
var description = "Toyota";
QuotingEngineEntities1 vehicles = new QuotingEngineEntities1();
List<object> list = new List<object>();
using (var context = new QuotingEngineEntities1())
{
var vehicle = from s in context.fn_GetVehicle(description)
select new
{
s.MAKE,
s.MODEL,
s.PRICE,
s.POWER,
s.Transmission
};
list.Add(vehicle.FirstOrDefault());
}
ViewBag.list = list;
return View(ViewBag.list);
}
AND MY View looks like this
#foreach (var v in ViewBag.list)
{
<li>#v.MODEL</li> //i get an error
<br />
}
I finally got it work.i had to loop through the data before adding it to the list.
public ActionResult Index()
{
var description = "Toyota";
List<fn_GetVehicle_Result> list = new List<fn_GetVehicle_Result>();
using (var context = new QuotingEngineEntities1())
{
var query = context.fn_GetVehicle(description);
foreach (var v in query)
{
list.Add(v);
}
ViewBag.list = list;
}
return View("Index",ViewBag.list);
}
enter code here
You are trying use Viewbag with your list data but it is not advisable way to do this and you dont have to add Viewbag into View() method. It is sent automatically into view by controller.
I would suggest to use ViewModel or ExpandoObject to send your collection into view. You can implement like following
//controller
public ActionResult Index()
{
using (var context = new QuotingEngineEntities1())
{
var vehicle = from s in context.fn_GetVehicle(description)
select new
{
s.MAKE,
s.MODEL,
s.PRICE,
s.POWER,
s.Transmission
};
dynamic yourmodel = new ExpandoObject();
yourmodel.Vehicles = vehicle.ToList();
}
return View(yourmodel);
}
// view
#using YourProject; // Your Project Name
#model dynamic
#foreach (var v in model.Vehicles)
{
<li>#v.MODEL</li>
<br />
}

Pass List To View C# Linq

public ActionResult Index()
{
ESSEntities DB = new ESSEntities();
List<EmployeeMdl> EmpList = DB.Employees.ToList();
return View(EmpList);
}
How do I pass this list to view because I got error
Cannot implicitly convert type '' to 'System.Collections.Generic.List'
You could do something like this.
public ActionResult Index()
{
ESSEntities DB = new ESSEntities();
List<Employees> lstDBEmployees = DB.Employees.ToList();
List<EmployeeMdl> EmpList = new List<EmployeeMdl>();
foreach(var thisEmployee in lstDBEmployees )
{
EmpList.Add(new EmployeeMdl(){
prop1 = thisEmployee.prop1,
prop2 = thisEmployee.prop2
});
}
return View(EmpList);
}
I think your view is not receiving List please use this.
View:
#model List<EmployeeMdl>
#foreach(var item in Model)
{
//code here
}
Controller:
public ActionResult Index()
{
ESSEntities DB = new ESSEntities();
List<EmployeeMdl> EmpList = DB.Employees.ToList();
return View(EmpList);
}
var EmpList =
DB.Employees.Select(c => new{ /*your model properties somthing like c.EmployeeId, c.EmployeeName*/}).ToList();
Try this.

Calling httppost actionresult from inside a view using a button

I have a project to make an online shop between users (post a product, buy, etc.) using a database. In this project I have a view called "ShoppingCart":
#model IEnumerable<MyFirstProject.Models.Product>
#{
ViewBag.Title = "ShoppingCart";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Your Shopping Cart</h2>
#if (Model == null)
{
<div style="float:left">Your cart is empty.</div>
<div>
Total payment: 0
</div>
}
else
{
decimal tPrice = 0;
<div>
<table style="float:left">
#foreach (var product in Model)
{
tPrice = tPrice + product.Price;
{ Html.RenderPartial("ProductLine", product);}
}
</table>
</div>
<div>
Total payment: #tPrice
</div>
}
It receives a list of products which the user decided to buy and displays them (not the important part). I need to add a button which will send the list to an action result in the "ShoppingController":
[HttpPost]
public ActionResult ShoppingCart(List<Product> bought)
{
if (ModelState.IsValid)
{
foreach (var listP in bought.ToList())
{
foreach (var databaseP in db.Products.ToList())
{
if (listP.ProductID == databaseP.ProductID)
{
databaseP.State = 1;
db.SaveChanges();
break;
}
}
}
return RedirectToAction("Index");
}
else
{
return View(bought);
}
}
"State" indicates if the product was bought or not (0=not bought, 1=bought), db is the database
If you wan't to post any data from a view to an action method, you should keep that data in form elements and keep that in a form. Since you want to post a collection of items, You may use Editor Templates.
Let's start by creating a view model.
public class ShoppingCartViewModel
{
public decimal TotalPrice { set; get; }
public List<Product> CartItems { set; get; }
}
public class Product
{
public int Id { set; get; }
public string Name { set; get; }
}
Now in your GET action, you will create an object of the ShoppingCartViewModel, load the CartItems property and send to the view.
public ActionResult Index()
{
var cart = new ShoppingCartViewModel
{
CartItems = new List<Product>
{
new Product { Id = 1, Name = "Iphone" },
new Product { Id = 3, Name = "MacBookPro" }
},
TotalPrice = 3234.95
};
return View(cart);
}
Now i will create an EditorTemplate. To do that, Go to your ~/Views/YourControllerName folder, and Create a directory called EditorTemplates and add a view with name Product.cshtml
The name of the file should match with the name of the type.
Open this new view and add the below code.
#model YourNamespace.Product
<div>
<h4>#Model.Name</h4>
#Html.HiddenFor(s=>s.Id)
</div>
You can keep the display however you want. But the important thing is, We need to keep a form field for the productId. We are keeping that in a hidden field here.
Now let's go back to our main view. We need to make this view strongly typed to our ShoppingCartViewModel. We will use the EditorFor html helper method in this view to call our editor template
#model ReplaceYourNamespaceHere.ShoppingCartViewModel
#using (Html.BeginForm())
{
#Html.EditorFor(x => x.CartItems)
<p>Total : #Model.TotalPrice</p>
<input type="submit" />
}
And in your HttpPost action method, We will have a paramer of type ShoppingCartViewModel. When the form is submitted, MVC Model binder will map the posted form values to an object of ShoppingCartViewModel.
[HttpPost]
public ActionResult Index(ShoppingCartViewModel model)
{
foreach (var item in model.CartItems)
{
var productId = item.Id;
// to do : Use productId and do something
}
return RedirectToAction("OrderSucessful");
}
You can iterate through the CartItems collection and get the Id of the Products and do whatever you want.
If you wan't to allow the user to edit the items (using a check box) in this page, Take a look at this answer. It is basically same, but you add a boolean property to Product class and use that for rendering a checkbox.

'object' does not contain a definition error in Asp.Net MVC

I am new in ASP.NET MVC.
I have a problem like below.
In Controller i have a code like this.
var students= db.Sagirdler.Where(x => x.SinifID == sinif.SinifID).
Select(m => new {m.Name, m.Surname}).ToList();
TempData["Students"] = students;
return RedirectToAction("Index", "MyPage");
This is my Index Action in MyPageController where I redirect and i call View.
public ActionResult Index()
{
ViewBag.Students = TempData["Students"];
return View();
}
And in View I use this code.
#{
ViewBag.Title = "Index";
var students = ViewBag.Students;
}
#foreach (var std in students)
{
#std.Name
<br/>
}
It says:
'object' does not contain a definition for 'Name'
What is the problem? How can I solve it?
You want to use
ViewBag.Students = students;
instead of TempData.
What I think you're trying to achieve would be better implemented like so:
Create a class
public class StudentViewModel
{
public string Name { get;set;}
public string Surname {get;set;}
}
then in your view using
#model IEnumerable<StudentViewModel>
#foreach (var student in Model)
{
...
}
And in your controller
var students = db.Sagirdler.Where(x => x.SinifID == sinif.SinifID)
.Select(m => new StudentViewModel { Name = m.Name, Surname = m.Surname} )
.ToList();
return View(students);

Categories

Resources