I have this in my View:
#{
var categories = (List<C_Category>)Model.c;
}
#foreach (C_Category cat in categories)
{
<option value="#cat.C_Id">#cat.C_Name</option>
}
And this in my Controller:
[HttpGet]
public ActionResult Admin()
{
using (var context = new sopingadbEntities())
{
List<P_Product> p = context.P_Product.OrderByDescending(x => x.P_Id).ToList();
List<C_Category> c = context.C_Category.ToList();
var ao = new AdminObj()
{
p = p,
c = c
};
return View("Admin", new { c, p });
}
}
But in my view I get an error:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' does not contain a definition for 'c'
I'm sure I've been doing this way all the time, am I missing something?
Here is the addwatch:
Error:
if u declare AdminObj as model in view than you have to pass var ao in return perameter
or
currently u are returning anonymous object as model in return view which is not work in view as you casted
mention what you added as #model in view
Answer extended:
Had to add this in the view as mentioned in this answer.
#model ProjectWeb.Controllers.HomeController.AdminObj
And in Controller:
[HttpGet]
public ActionResult Admin()
{
using (var context = new sopingadbEntities())
{
List<P_Product> p = context.P_Product.OrderByDescending(x => x.P_Id).ToList();
List<C_Category> c = context.C_Category.ToList();
var ao = new AdminObj()
{
p = p,
c = c
};
return View(ao);
}
}
Related
In my ASP.NET MVC application, I'm trying to pass some values from controller to view.
For this, I'm using the view bag method.
From the controller, the data is passed to the view.
In the view within the for each loop, it also shows the data in the view bag.
But when it runs, I'm getting an error 'object' does not contain a definition for 'cusName'
This is the controller
var SuggestionList = (from c in db.tbl_Main
where c.Suggestion != null orderby c.CreatedDate descending select new
{
cusName = c.CustomerName,
Suggest = c.Suggestion
}).Take(3).ToList();
ViewBag.suggestList = SuggestionList;
return View();
In the view
#foreach(var data in ViewBag.suggestList) {
<li > #data.cusName < /li>
}
Would suggest creating a model class (concrete type) and returning it as List<ExampleModel> type instead of an anonymous list.
public class ExampleModel
{
public string CusName { get; set; }
public string Suggest { get; set; }
}
var SuggestionList = (from c in db.tbl_Main
where c.Suggestion != null
orderby c.CreatedDate descending
select new ExampleModel
{
CusName = c.CustomerName,
Suggest = c.Suggestion
})
.Take(3)
.ToList();
ViewBag.suggestList = SuggestionList;
return View();
How can I remove a record from List in MVC 4 ASP.NET by click on Delete button Here I am not using any database I want to delete a record from list which I have define in controller. without any database remove a record from list using delete action
StudentController
public class StudentController : Controller
{
//
// GET: /Student/
public ActionResult Index()
{
List<StudentVM> students = new List<StudentVM>();
StudentVM obj1 = new StudentVM();
obj1.Name = "Zeeshan";
obj1.id = "1";
obj1.Address = "Lahore";
students.Add(obj1);
StudentVM obj2 = new StudentVM();
obj2.Name = "Zeshan";
obj2.id = "2";
obj2.Address = "Lahore";
students.Add(obj2);
return View(students);
}
public ActionResult Delete(string? i)
{
List<StudentVM> students = new List<StudentVM>();
var st = students.Find(c => c.id = i);
students.Remove(st);
return View("Index");
}
}
View
#model List<Activity2.Models.StudentVM>
#{
ViewBag.Title = "Index";
}
<table border="1">
<tr>
<th>Id</th>
<th>Name</th>
<th>Address</th>
</tr>
#foreach (var obj in Model)
{
<tr>
<td>#obj.id</td>
<td>#obj.Name</td>
<td>#obj.Address</td>
<td>#Html.ActionLink("Delete","Delete",new{i = obj.id}) </td>
</tr>
</table>
}
Error
Error 1 The type 'string' must be a non-nullable value type in order
to use it as parameter 'T' in the generic type or method
'System.Nullable'
Error 3 Cannot implicitly convert type 'string?' to 'string'
You are trying to use nullable reference-types which is a feature of C# 8.0 (which hasn't been released yet). In order to fix your errors you'd have to change your string? i to string i.
To remove items from the list you'd have to create it outside of your Index() and make it static, so other Endpoints like Delete() are able to access the list. That way each time somebody accesses the Index of your Controller two new students are added to the List (probably not the behavior you'd want in the long run, i just copied your code on this one):
public class StudentController : Controller
{
private static readonly List<StudentVM> _students = new List<StudentVM>();
public ActionResult Index()
{
StudentVM obj1 = new StudentVM();
obj1.Name = "Zeeshan";
obj1.id = "1";
obj1.Address = "Lahore";
_students.Add(obj1);
StudentVM obj2 = new StudentVM();
obj2.Name = "Zeshan";
obj2.id = "2";
obj2.Address = "Lahore";
_students.Add(obj2);
return View(students);
}
public ActionResult Delete(string i)
{
var student = _students.FirstOrDefault(c => c.id == i);
if(student == null){ /* Failed to find student */ }
_students.Remove(student);
return View("Index");
}
}
Also there seems to be an Error in your View code. The </table> should be outside of the foreach.
Firstly, as the error message is clearly saying you need to use string instead of string?:
public ActionResult Delete(string i)
And secondly you should be aware that, MVC is stateless because HTTP is. So this code won't delete the record as per your expectation. In order to make this code works, you need to use Session. Something like this:
if(Session["StudentVM"] == null)
{
//Your Code
Session["StudentVM"] = students;
}
And:
public ActionResult Delete(string i)
{
List<StudentVM> students = Session["StudentVM"] as List<StudentVM>;
var st = students.Find(c=>c.id=i);
//The rest of your code...
}
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 />
}
I have the follow code in the controller
public ActionResult Linq()
{
List<region> Regiones = db.region.ToList();
List<comuna> Comunas = db.comuna.ToList();
var resultado = from r in Regiones
join c in Comunas on r.r_id equals c.c_region
where r.r_id == 8
select new
{
region = r.r_region,
comuna = c.c_comuna
};
ViewBag.resultado = resultado;
return View();
}
and this in the view
#{
foreach(var a in ViewBag.resultado)
{
<tr><td>
#a.comuna
</td></tr>
}
}
but when this run, i have the follow error:
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: 'object' no contiene una definiciĆ³n para 'comuna'.
What happened? how I print all "comuna" in the view?
Thanks!
One of possible solution is create a new type for result like
public class Address //some good name
{
public int Region {get;set;};
public string Comuna {get;set;} ;
}
them modify your action
public ActionResult Linq()
{
List<region> Regiones = db.region.ToList();
List<comuna> Comunas = db.comuna.ToList();
var resultado = from r in Regiones
join c in Comunas on r.r_id equals c.c_region
where r.r_id == 8
select new Address
{
Region = r.r_region,
Comuna = c.c_comuna
};
return View(resultado);
}
and change view:
#model System.Collections.Generic.IEnumerable<Address>
#{
foreach(var a in Model)
{
<tr><td>
#a.Comuna
</td></tr>
}
}
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);