EditorForModel() not working - asp.net-mvc

I am using EditorForModel() to populate Data
Index Method :
public ActionResult Index()
{
SampleDbContext db = new SampleDbContext();
return View(db.Employees.ToList());
}
Index View :
#model IEnumerable<MultipleRowsDemo.Models.Employee>
<div style="font-family:Aria">
#using (Html.BeginForm())
{
<table border="1">
<thead>
<tr>
<th>
Select
</th>
<th>
Name
</th>
<th>
Email
</th>
</tr>
</thead>
<tbody>
#Html.EditorForModel()
</tbody>
</table>
}
</div>
but it is not working. It displays data like
123 Select Name Email
I read similar posts
EditorForModel and DisplayForModel do not work then passing class model within class model
It is suggested not use complex properties. I don't have one.
Another one is.
Displaying entities data with EditorForModel
It suggested to use
#using(Html.BeginForm())
{
...
}
I already have this.

Your Class Entity Name should match with the Name of the Template
Eg: If your ADO.net Employee entity name is "Employee" then the name of the template should be "Employee.cshtml" in Shared folder under Views directory

Related

Incorrent model passed to Partial View

This might be a duplicate question but I can't for the life of me know what the solution is. I'm trying to load a partial view with a table based on the ID of a clicked link.
I'm getting this error:
System.InvalidOperationException: 'The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List`1[MasigasigTrackingSystem.Models.Invoice]', but this ViewDataDictionary instance requires a model item of type 'MasigasigTrackingSystem.Pages.Masigasig.MainPage.TripTicket.TripTicketListModel'.'
I can't seem to figure out how should I passed the model to the partial view.
Here is what my OnGet looks like:
public IList<Invoice> Invoice { get; set; }
public PartialViewResult OnGetDetails(int TripTicketID)
{
var invoices = from m in _context.Invoice
select m;
invoices = invoices.Where(x => x.TripTicketID == TripTicketID);
Invoice = invoices.ToList();
return Partial("_TripTicketListDetails", Invoice);
}
Here is my partial view:
#model TripTicketListModel
<h1>Hello, test</h1>
<table id="TripEntryList" class="table table-bordered table-hover">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Invoice[0].InvoiceNumber)
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Invoice)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.InvoiceNumber)
</td>
</tr>
}
</tbody>
You Partial View Required TripTicketListModel and you are passing the model Invoice. It means you are passing wrong model.
From your View code i can say your Invoice is used inside TripTicketListModel, so try below solution.
public PartialViewResult OnGetDetails(int TripTicketID)
{
var invoices = from m in _context.Invoice select m;
invoices = invoices.Where(x => x.TripTicketID == TripTicketID);
TripTicketListModel model = new TripTicketListModel();
model.Invoice = invoices.ToList();
return Partial("_TripTicketListDetails", model);
}

Partial View is not rendering td elements inside foreach razor tag

I am using a List of Products as a Model for my Partial view. In the partial view I am using a foreach loop to get the values of Product class and trying to render it to users. In the partial view I've written this code:
#model Project.ViewModel.ListofProductsVM
#using Project.Models
<table>
<tr>
<th>
Name
</th>
<th>
Cost
</th>
</tr>
#{
foreach (Products prod in Model.products)
{
<tr>
<td>#prod.Name.ToString()</td>
<td>#prod.Cost.ToString()</td>
</tr>
}
}
</table>
I can see the headers "Name" and "Cost" in the page but Product Name and its Cost is not rendering. When I am checking the source code in HTML it is showing me this HTML only:
<table>
<tr>
<th>
Name
</th>
<th>
Cost
</th>
</tr>
</table>
While debugging I can see the values are correctly getting passed to Partial Views. Even the "#prod.Name" and "#prod.Cost" is showing me the correct value. But it is not rendering it to HTML. I don't understand what I am doing wrong here. Thanks in advance.
The #{ } means that this is c# code block, you can fix the problem by writing your foreach loop code this way:
#foreach (Products prod in Model.products)
{
<tr>
<td>#prod.Name.ToString()</td>
<td>#prod.Cost.ToString()</td>
</tr>
}
and if you want to stick with your way then you have to specify to render that as html like:
#{
foreach (Products prod in Model.products)
{
#:<tr>
#:<td>#prod.Name.ToString()</td>
#:<td>#prod.Cost.ToString()</td>
#:</tr>
}
}
I had a similiar problem. In my case, all I needed was to add "#" before the foreach nested in an if statement. This is a pared down snippet of my working code
C# Model class:
public class MyModel
{
public string FirstName{ get; set; }
public string LastName{ get; set; }
}
CSHTML file:
#model List<MyProject.Models.MyModel>
#if (Model.Count > 0)
{
<div class="row" >
<table>
#foreach (var item in Model)
{
<tr>#item.FirstName #item.LastName</tr>
}
</table>
</div>
}
But it's the same answer that another user gave you.

Sending piece of model data back to controller as variable

I have a view which imports data from a model and I need to make action links that send back a piece of the model data back to the controller
Index.cshtml
#model IEnumerable<App.Models.User>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Number)
</th>
<th>
#Html.ActionLink("Request", "Index", new { userNumber = //model.Number value })
</th>
</tr>
</table>
I have tried:
new { userNumber = model.Number }) //The name model does not exist in the current context
new { userNumber = Model.Number }) //IEnumerable does not contain a definition for ModelNumber (even though it does)
Since you are using a collection of users as your model, you need to iterate over your model with a foreach loop to get the values present on App.Models.User. The Number property would presumably be on your App.Models.User class, not on IEnumerable<App.Models.User>.
Something like this would work:
#foreach(App.Models.User user in Model) {
Html.ActionLink("Request", "Index", new { userNumber = user.Number })
}
Under your Views\Shared folder, add a DisplayTemplates folder.
Inside that folder, create a view called User.cshtml.
Add this:
<tr>
<th>
#Html.DisplayNameFor(model => model.Number)
</th>
<th>
#Html.ActionLink("Request", "Index", new { userNumber = model.Number })
</th>
</tr>
Then in your view, add this:
<table>
#Html.DisplayFor(model => model)
</table>

Why is DisplayForModel not showing the expected output?

I have a simple razor page, where the first part correctly shows information from each element in my model in a table. After that I'm trying to use DisplayFor to show me every property in the model, but it generates 123 for each iteration. What am I doing wrong?
#model System.Data.Entity.IDbSet<DBFramework.MyPerson>
#{
ViewBag.Title = "Home Page";
}
<p></p>
<table border="1">
<thead>
<tr>
<th style="width:300px;">Name</th>
<th style="width:300px;">Age</th>
</tr>
</thead>
#foreach (var p in Model)
{
<tr>
<td>#Html.Label(p.Name)</td>
<td>#Html.Label(p.Age.ToString())</td>
</tr>
}
</table>
#foreach (DBFramework.MyPerson x in Model)
{
#Html.DisplayForModel(x)<br/>
}
Creates the following output:
Name Age
Mike 40
Penny 1
Kunal 30
123
123
123
Try this:
#foreach (var item in Model)
{
#Html.DisplayFor(model => item)
}
DisplayFor and DisplayForModel are used with templates in Views\Shared\DisplayTemplates.
When you call DisplayForModel, it will take the page model (Model) and if you specify a parameter, will try to load the template with the name provided (if string) or add the object as additional data in ViewData. When you called:
#foreach (DBFramework.MyPerson x in Model)
{
#Html.DisplayForModel(x)<br/>
}
You told it - Display Model which is type System.Data.Entity.IDbSet<DBFramework.MyPerson> and add MyPerson in the template ViewData. Do this 3 times. You also didn't give him a hint to select a DisplayTemplate and it will try to use convention to find it.
As Bappi Datta said, if you want to display a template for MyPerson, you need to call:
#foreach (var item in Model)
{
#Html.DisplayFor(model => item)
}
However, you need a MyPerson display template created which accepts #model DBFramework.MyPerson to render the item or it will simply do a .ToString() by default I believe.

Accepting A IENUMERABLE model post in a controller in mvc 3 vb.net?

I have a view in my app that uses a #modeltype ienumerable of (xxxxxxx.abc), and uses a for each loop to populate the view. This view has select boxes that show up next to each item in the view. When I post the form to the controller accepting it as a formcollection does not work, and if I accept it like: ByVal abc as abc it says that its an invalid model.. The code is as follows:
<AcceptVerbs(HttpVerbs.Post)>
Function ClassAttendance(ByVal Attendance As Attendance) As ActionResult
If ModelState.IsValid Then
UpdateModel(Attendance)
db.SaveChanges()
Return RedirectToAction("Index")
End If
Return View()
End Function
Any ideas?? Can I somehow use a for each loop in the view without making it ienumerable? If so when It posts to the controller my below code would just about work.. The only value that really matters is the selectlist choice and the id of the record that it was changed for...
The view is:
#ModelTYPE List(Of xxxxx.attendance)
#Code
ViewData("Title") = "Class Attendance Record"
End Code
#Using Html.BeginForm
#<fieldset>
<table>
<tr>
<th>
First Name
</th>
<th>
Last Name
</th>
<th>
Registrant ID
</th>
<th>
Course Status
</th>
<th>
Comments
</th>
</tr>
#For r As Integer = 0 To ViewBag.count
Dim i As Integer = r
#Html.HiddenFor(Function(m) m(i).id)
#<tr>
<td>
#Html.DisplayFor(Function(m) m(i).firstName)
</td>
<td>
#Html.DisplayFor(Function(m) m(i).lastName)
</td>
<td>
#Html.DisplayFor(Function(m) m(i).reg_id)
</td>
<td>
#Html.DisplayFor(Function(m) m(i).Completed_Class)
</td>
<td>
#Html.DropDownList("Completed_Class", New SelectList(ViewBag.courseStatus, "Status", "Status"))
</td>
<td>
#Html.TextBoxFor(Function(m) m(i).Comments, New With {.class = "AttenComment"})
</td>
</tr>
Next
</table>
<p>
<input type="submit" name="submit" />
</p>
</fieldset>
End Using
I have been over countless tut's and posts with no luck at all... I only want to update the model record for each record to the corresponding selected value from the selectlist... Thanks greatly for any and all help..
In brief, this can be done. There are many ways to accomplish this, the easiest by far I found was to have a custom view model which contains an array of the model you want to bulk insert.
public class MultipleAttendance
{
public Attendance[] attendances {get;set;}
}
Then in your View you can loop as such:
#for(int i=0,i<10;i++)
{
#Html.TextBox(attendances[i].firstName)
}
In the controller
[HttpPost]
public ActionResult Create(MultipleAttendance model)
{
// Get a value
model.attendances[0].firstName;
}
Hope it helps :)

Resources