submit only checked items - c#

I'm trying to submit only these rows which is checked. I'm using this jquery plungin and my table looks same as is in link
#model IEnumerable<BillBox.ACD_UNI_STUDENTS>
<table class="table tblSelect">
<tr>
<th>
<input type="checkbox" id="checkall" title="Select all" />
</th>
<th>
#Html.DisplayNameFor(model => model.FIRST_NAME)
</th>
<th>
#Html.DisplayNameFor(model => model.LAST_NAME)
</th>
<th>
#Html.DisplayNameFor(model => model.PERSONAL_NUMBER)
</th>
<th>
#Html.DisplayNameFor(model => model.ACD_UNI_DEGREES.DEGREE)
</th>
<th>
#Html.DisplayNameFor(model => model.ACD_UNI_FACULTIES.FACULTY)
</th>
<th>
#Html.DisplayNameFor(model => model.ACD_UNI_SEMESTERS.SEMESTER)
</th>
<th>
#Html.DisplayNameFor(model => model.ACD_UNI_SPECIALIZATIONS.SPECIALIZATION)
</th>
<th>
#Html.DisplayNameFor(model => model.COR_PAYER_STATUS.NAME)
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
<input type="checkbox"/>
</td>
<td>
#Html.DisplayFor(modelItem => item.FIRST_NAME)
</td>
<td>
#Html.DisplayFor(modelItem => item.LAST_NAME)
</td>
<td>
#Html.DisplayFor(modelItem => item.PERSONAL_NUMBER)
</td>
<td>
#Html.DisplayFor(modelItem => item.ACD_UNI_FACULTIES.FACULTY)
</td>
<td>
#Html.DisplayFor(modelItem => item.ACD_UNI_SEMESTERS.SEMESTER)
</td>
<td>
#Html.DisplayFor(modelItem => item.ACD_UNI_SEMESTERS.SEMESTER)
</td>
<td>
#Html.DisplayFor(modelItem => item.ACD_UNI_SPECIALIZATIONS.SPECIALIZATION)
</td>
<td>
#Html.DisplayFor(modelItem => item.COR_PAYER_STATUS.NAME)
</td>
</tr>
}
</table>
Now I have a question. How can I retrieve only these rows which checkbox is checked?
that's my controller
public PartialViewResult AllStudent()
{
var students = (from q in db.ACD_UNI_STUDENTS
select q).ToList();
return PartialView(students);
}
there are many rows (from db) so I can't do it with formcollection. I can't retrieve their names

You may submit the selected ids as IEnumerable and then filter them in your controller! Here is an example
<form action="url" method="post">
...
#foreach (var item in Model)
{
<tr>
<td>
<input type="checkbox" name="Objs[]" id="Objs[]" value="#item.UNIQUE_ID"/>
</td>
<td>
#Html.DisplayFor(modelItem => item.FIRST_NAME)
</td>
</tr>
}...
</form>
and your controller
[HttpPost]
public PartialViewResult AllStudent(IEnumerable<long> Objs)
{
var students = (from q in db.ACD_UNI_STUDENTS
where Objs.Contains(q.UNIQUE_ID)
select q).ToList();
return PartialView(students);
}
...

I'd suggest not to use the Database Model for the View directly. You should have a Model to bind to the Rows, which might look like:
public class StudentRowViewModel
{
public bool IsChecked { get; set; }
public int StudentId { get; set; }
// ... More columns, whatever you want to display
public string Name { get; set; }
}
When populating the View, you select StudentRowViewModels like this:
db.ACD_UNI_STUDENTS.Select(x => new StudentRowViewModel { StudentId = x.UNIQUE_ID, Name = ... });
Or whatever applies to your DataBase Model.
In your View, your Checkbox will also Bind to the Model:
#Html.CheckboxFor(x => x.IsChecked)
Finally, when the Form is submitted, you can select only the checked Items:
public ActionResult AllStudents(IEnumerable<StudentRowViewModel> model)
{
var checked = model.Where(x => x.IsChecked).Select(x => x.StudentId).ToList();
var items = db.ACD_UNI_STUDENTS.Where(x => checked.Contains(x.UNIQUE_ID));
}
You get the Idea?

First put a class and value attribute in your checkbox :
<input type="checkbox" class="myCheckBox" value="#item.PERSONAL_NUMBER" />
Then i advise you to use a JQuery script to detect which checkbox are checked :
I suppose that you have a button to do another action :
$(document).ready(function () {
$('#myButton').click(function() {
var id = '';
$('.myCheckBox:checked').each(function (e) {
id += $(this).val() + ';'
}
var url = '/ControllerName/ActionResultName';
$.ajax({
url:url,
cache: false,
type: 'POST',
data: {
Id: id
},
succes: function(data){
$('.myCheckBox').attr('checked',false);
location.reload();
}
})
}
});
After that you can get in your controller all the personnal numbers in your controller :
put a string parameter 'id' to your actionresult.
id.TrimEnd(';')

Related

Count number of ids for each id in table

I have two tables. One is Booking and other is Course. Course can have many Bookings.
I want to count number of Bookings for each Course and pass that to ViewBag. So I want to count how many users applied for each Course.
This line counts total number o Bookings but I cant figure out how to do that for each Course.
ViewBag.Counter = db.Bookings.Count();
This line gets all the courses to my Index page.
IEnumerable<Course> courses = cr.GetCourses();
return View(courses.ToList());
And this is controller that is doing the work. I tried with 2 foreach loops but cant get it to work.
public ActionResult Index()
{
Booking booking = new Booking();
Course course = new Course();
List<Course> listCourses = new List<Course>();
List<Booking> bookings = new List<Booking>();
foreach (var item in listCourses)
{
int id = course.CourseId;
foreach (var item1 in bookings)
{
ViewBag.Counter = db.Bookings.Where(x => x.CourseId == id).Count();
}
}
IEnumerable<Course> courses = cr.GetCourses();
return View(courses.ToList());
}
I expect to get a number of users that applied for each course that is listed on my index page. I got no exceptions or errors and nothing shows up in my view. When I use ViewBag.Counter = db.Bookings.Count(); I get a total number of users that applied for all avaliable courses. Model on the view is Course model which is in relation with Booking with one to many relation.
This is the View for my ActionResult.
#model IEnumerable<Entities.Course>
#{
ViewBag.Title = "AlgebraSchoolApp";
}
<h2>Dobrodošli!</h2>
<p>
Da bi se prijavili na neki od naših tečajeva kliknite na link prijave:
<button>
#Html.ActionLink("Prijava","Create","Booking")
</button>
</p>
<h2> Svi tečajevi</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CourseName)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayName("Broj polaznika")
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CourseName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#ViewBag.Counter
</td>
</tr>
}
</table>
<h2>Slobodni tečajevi</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CourseName)
</th>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.Date)
</th>
</tr>
#foreach (var item in Model.Where(x => x.Full == false))
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CourseName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Date)
</td>
</tr>
}
</table>
The reason that ViewBag.Counter is showing the same result for all courses is because it is being overwritten each time with ViewBag.Counter = db.Bookings.Where(x => x.CourseId == id).Count();.
If i have understood your issue this can be fixed by creating a new view model to store the required information for a course and return this to your view. EG:
public class CourseViewModel
{
public string CourseName { get; set; }
public string Description { get; set; }
//etc
public int BookingCount { get; set; }
}
Controller:
public ActionResult Index()
{
var courses = cr.GetCourses();
var courseViewModels= new List<CourseViewModel>();
foreach (var course in courses )
{
var bookingCount = db.Bookings.Where(x => x.CourseId == course.CourseId).Count();
courseViewModels.Add(new CourseViewModel{
CourseName = course.CourseName, //Add all the vm properties
BookingCount = bookingCount
});
}
return View(courseViewModels);
}
In the view:
#model IEnumerable<CourseViewModel>
#/*...*/
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CourseName)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.BookingCount )
</td>
</tr>
}

Combine 2 ILists of different classes into 1 IList joined on a common property

I have 2 filled ILists Suppliers and VwSrmAhmSuppliers with a common property Supplier.SupplierNo and VwSrmAhmSupplier.AhmSupplierNo. I'd like to combine them on that common property into one IList where the individual class properties are still accessible so I can efficiently access them in the View.
So if I pulled the first item in CommonList and then asked for CommonList(1).Supplier.SupplierNo and CommonList(1).VwAhmSrmSupplier.AhmSupplierNo - those 2 fields would be the same.
Maybe I have a class like this:
public class SupplierDetail
{
public Supplier Supplier { get; set; }
public Models.ExternalData.VwSrmAhmSupplier VwSrmAhmSupplier { get;set;}
}
public IList<Supplier> Suppliers { get;set; }
public IList<Models.ExternalData.VwSrmAhmSupplier> VwSrmAhmSuppliers { get; set; }
public IList<SupplierDetail> SupplierDetails;
public async Task OnGetAsync(Boolean? All)
{
//don't show all records unless explicity asked to!
if (All == true)
{
Suppliers = await _context.Supplier
.Include(s => s.Status)
.Include(c => c.Category)
.Include(c => c.Comments)
.OrderByDescending(c => c.CreateDate)
.ToListAsync();
var supplierNos = Suppliers.Select(s => s.SupplierNo).ToList();
VwSrmAhmSuppliers = await _externalcontext.VwSrmAhmSuppliers
.Where(v => supplierNos
.Any(s => s == v.AhmSupplierNo))
.ToListAsync();
SupplierDetails = ??
}
The HTML table I'm trying to generate would be something like this:
<tbody>
#foreach (var item in Model.CommonList)
{
<tr>
<td>
<a asp-page="./Details" asp-route-id="#item.Id">#Html.DisplayFor(modelItem => item.Supplier.SupplierNo)</a>
</td>
<td>
#Html.DisplayFor(modelItem => item.VwSrmAhmSupplier.AhmSupplierNm)
</td>
<td>
#Html.DisplayFor(modelItem => item.Supplier.CreateDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Supplier.Creator)
</td>
<td>
#Html.DisplayFor(modelItem => item.Supplier.Category.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Supplier.Status.Description)
</td>
<td>
<a asp-page="./Delete" asp-route-id="#item.Id" class="btn btn-danger">Hide</a>
</td>
</tr>
}
</tbody>
Thanks #Selvin for the help in leading me down the right path.
Create a composite class of 2 classes
public class SupplierDetail
{
public Supplier Supplier { get; set; }
public VwSrmAhmSupplier VwSrmAhmSupplier { get;set;}
}
Then, fill the list by looping:
SupplierDetails = new List<SupplierDetail>();
foreach (Supplier supplier in Suppliers)
{
SupplierDetail supplierDetail = new SupplierDetail
{
Supplier = supplier,
VwSrmAhmSupplier = VwSrmAhmSuppliers.Where(s => s.AhmSupplierNo == supplier.SupplierNo).First()
};
SupplierDetails.Add(supplierDetail);
}
Finally, access your object properties in the view
<table id="table" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.SupplierDetails[0].Supplier.SupplierNo)
</th>
<th>
#Html.DisplayNameFor(model => model.SupplierDetails[0].VwSrmAhmSupplier.AhmSupplierNm)
</th>
<th>
#Html.DisplayNameFor(model => model.SupplierDetails[0].Supplier.CreateDate)
</th>
<th>
#Html.DisplayNameFor(model => model.SupplierDetails[0].Supplier.Creator)
</th>
<th>
#Html.DisplayNameFor(model => model.SupplierDetails[0].Supplier.Category)
</th>
<th>
#Html.DisplayNameFor(model => model.SupplierDetails[0].Supplier.Status)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.SupplierDetails)
{
<tr>
<td>
<a asp-page="./Details" asp-route-id="#item.Supplier.Id">#Html.DisplayFor(modelItem => item.Supplier.SupplierNo)</a>
</td>
<td>
#Html.DisplayFor(modelItem => item.VwSrmAhmSupplier.AhmSupplierNm)
</td>
<td>
#Html.DisplayFor(modelItem => item.Supplier.CreateDate)
</td>
<td>
#Html.DisplayFor(modelItem => item.Supplier.Creator)
</td>
<td>
#Html.DisplayFor(modelItem => item.Supplier.Category.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Supplier.Status.Description)
</td>
<td>
<a asp-page="./Delete" asp-route-id="#item.Supplier.Id" class="btn btn-danger">Hide</a>
</td>
</tr>
}
</tbody>
</table>

Why parameter of the action method is null when view is posted?

This is an ASP.NET MVC project. I have a view that displays a collection of BookRentViewModel items.
When I click on the button in the view, the view is posted to an action method called rent. rent action method has a parameter called items of type IEnumerable<BookRentViewModel>.
Here is the code of the view:
#model IEnumerable<DaramSerl.Models.ViewModels.BookRentViewModel>
#using (Html.BeginForm("rent", "RentBook", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.bookName)
</th>
<th>
#Html.DisplayNameFor(model => model.isRented)
</th>
<th>
#Html.DisplayNameFor(model => model.startDate)
</th>
<th>
#Html.DisplayNameFor(model => model.endDate)
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.EditorFor(modelItem => item.bookName)
</td>
<td>
#Html.EditorFor(modelItem => item.isRented)
</td>
<td>
#Html.EditorFor(modelItem => item.startDate)
</td>
<td>
#Html.EditorFor(modelItem => item.endDate)
</td>
</tr>
}
</table>
<input type="submit" value="Create" class="btn btn-primary" />
}
And here is the action method:
[HttpPost]
public async Task<ActionResult> rent(IEnumerable<BookRentViewModel> items)
{
if (ModelState.IsValid)
{
return RedirectToAction("/Index");
}
return View();
}
And here is the BookRentViewModel:
public class BookRentViewModel
{
[Key]
public int bookId{ get; set; }
public string bookName { get; set; }
public bool isRented { get; set; }
public DateTime startDate { get; set; }
public DateTime endDate { get; set; }
}
The problem is that items parameter is always null when rent action is triggered.
Any idea why items is null and does not get the collection from the view?
UPDATE
I used fiddler to see if the collection is posted to the server but it seems it cannot be parsed into BookRentViewModel items.
UPDATE3
Here is screenshot from fiddler with the collection sent from the view:
Doesnt look like you're setting a value for public int bookId - if thats the case this will fail validation as its a non-nullable type.
Either way, set a breakpoint in your controller method and check the errors on ModelState - see Get error message if ModelState.IsValid fails?
Edit
To include properties but not show them on your view, use the hidden field razor tag helper:
#Html.HiddenFor(x => x.bookId)
I tried reproduce source code.
You can change model mapping in cshtml file as below
#for (int i = 0; i < Model.Count();i++ )
{
<tr>
<td>#Html.TextBox("items[" + #i + "].bookName",
Model.ElementAt(i).bookName
)</td>
<td>#Html.CheckBox("items[" + #i + "].isRented",
Model.ElementAt(i).isRented
)</td>
<td>#Html.TextBox("items[" + #i + "].startDate",
Model.ElementAt(i).startDate
)</td>
<td>#Html.TextBox("items[" + #i + "].endDate",
Model.ElementAt(i).endDate
)</td>
</tr>
}
rent.cshtml file
#model IEnumerable<WebApplication2.Controllers.BookRentViewModel>
#using (Html.BeginForm("rent", "Rent", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.bookName)
</th>
<th>
#Html.DisplayNameFor(model => model.isRented)
</th>
<th>
#Html.DisplayNameFor(model => model.startDate)
</th>
<th>
#Html.DisplayNameFor(model => model.endDate)
</th>
</tr>
#*#foreach (var item in Model)
{
<tr>
<td>
#Html.EditorFor(modelItem => item.bookName)
</td>
<td>
#Html.EditorFor(modelItem => item.isRented)
</td>
<td>
#Html.EditorFor(modelItem => item.startDate)
</td>
<td>
#Html.EditorFor(modelItem => item.endDate)
</td>
</tr>
}*#
#for (int i = 0; i < Model.Count();i++ )
{
<tr>
<td>#Html.TextBox("items[" + #i + "].bookName",
Model.ElementAt(i).bookName
)</td>
<td>#Html.CheckBox("items[" + #i + "].isRented",
Model.ElementAt(i).isRented
)</td>
<td>#Html.TextBox("items[" + #i + "].startDate",
Model.ElementAt(i).startDate
)</td>
<td>#Html.TextBox("items[" + #i + "].endDate",
Model.ElementAt(i).endDate
)</td>
</tr>
}
</table>
<input type="submit" value="Create" class="btn btn-primary" />
}

ASP.NET passing List back to controller from IEnumerable #model inside Table header ActionLink with non-indexing

I have been reviewing possible ways to return a View's #model information which is of type IEnumerable back to the controller, so that if I sort/filter on a query from database, I can refine the return each iteration without restarting with a fresh full list being returned. All the ways show you need to POST back based on model[index] which works if you are inside a for loop. But I am working with sending the collection back from an #HTML.ActionLink within a table's header section, so there is no possible indexing available.
My WebAPI setup is based on this where they show how to sort and filter. I am trying to make it a little more complex in that after I filter a list based on my original DB query, I will then be able to sort (from a clickable-actionLink on a table's header column) from that filtered list; where as currently it would just sort from a fresh complete list.
The only way I can think of to do this is pass back (by a POST) to the controller the updated list of the customClass.
#Html.ActionLink("Name", "Index", new { orderBy = ViewBag.sortByName,
companyListIds = Model.???? })
A better option (based on comments from Tacud) which would require a smaller POST URL would be by returning a list of the id properties only which can then be applied to a query. But its still a list and still needs to be sent back without an index from and ActionLink. This will help keep track and allow me to continue drilling down to a smaller and smaller list.
Below is parts of my model class, the index Action from the controller, and the index view.
Model namespace:
public class Company
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string State { get; set; }
}
Controller Namespace:
public async Task<IActionResult> Index(ICollection<int> prev, string orderBy , string searchCategory ="", string searchString = "")
{
List<string> Categories = new List<string>() { "Name", "City", "State", "Zip", "Contact Person" };
ViewBag.searchCategory = new SelectList(Categories);
ViewBag.sortByName = orderBy == null ? "name" : orderBy == "name" ? "namedesc" : "name";
ViewBag.sortByCity = orderBy == "city" ? "citydesc" : "city";
ViewBag.sortByState = orderBy == "state" ? "statedesc" : "state";
ViewBag.companyIndex = companyList.Count==0 ? await _context.Company.ToListAsync() : companyList ;
List<Company> resultSet = new List<Company>(ViewBag.companyIndex);
if (!String.IsNullOrEmpty(searchCategory) && !String.IsNullOrEmpty(searchString))
{
switch (searchCategory)
{
.....
}
}
switch (orderBy)
{
....
}
return View(resultSet);
}
View namespace:
#model IEnumerable<Laier_It.Models.Company> <p>
#using (Html.BeginForm() {
<p>
Search By: #Html.DropDownList("SearchCategory", "")
Search For: #Html.TextBox("SearchString")
<input type="submit" value="Filter" />
</p> }
<table class="table ">
<thead>
<tr>
<th>
#Html.ActionLink("Name", "Index", new { orderBy = ViewBag.sortByName, companyList = Model })
</th>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<th>
#Html.ActionLink("City", "Index", new { orderBy = ViewBag.sortByCity, companyList = Model })
</th>
<th>
#Html.ActionLink("State", "Index", new { orderBy = ViewBag.sortByState, companyList = Model })
</th> </tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
#Html.DisplayFor(modelItem => item.State)
</td> </tr>
}
</tbody>
</table>
To first obtain the list of Id's that I want to post back to the controller of the current rendition showing within the WebAPI view page I used #Model.Select(x => x.Id)
My controller index method was only changed by this
var resultSet = prev.Count == 0 ? await _context.Company.ToListAsync() :
await _context.Company.Where(x => prev.Contains(x.Id)).ToListAsync();
And my View looks like this:
#model IEnumerable<Laier_It.Models.Company>
#using (Html.BeginForm() )
{
<p>
Search By: #Html.DropDownList("SearchCategory", "")
Search For: #Html.TextBox("SearchString")
<input type="submit" value="Filter" />
</p>
}
<table class="table ">
<thead>
<tr>
<th>
#Html.ActionLink("Name", "Index", new { orderBy = ViewBag.sortByName, prev = #Model.Select(x => x.Id) } )
</th>
<th>
#Html.DisplayNameFor(model => model.Address)
</th>
<th>
#Html.ActionLink("City", "Index", new { orderBy = ViewBag.sortByCity, prev = #Model.Select(x => x.Id) } )
</th>
<th>
#Html.ActionLink("State", "Index", new { orderBy = ViewBag.sortByState, prev = #Model.Select(x => x.Id) } )
</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Address)
</td>
<td>
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
#Html.DisplayFor(modelItem => item.State)
</td>
</tr>
}
</tbody>
</table>

Populate form from table select with asp.net mvc

I have a table with data, how can I populate a form on the same page with the data when the edit button is clicked. Basically is should be the same as this example but without using knockoutjs
http://jsfiddle.net/jiggle/2cr2f/
#model IEnumerable<GenomindApp2.Areas.RulesEngine.ViewModels.GeneViewModel>
#{
ViewBag.Title = "Index2";
}
<table>
<tr>
<th>
#Html.DisplayNameFor(model => model.GeneValue)
</th>
<th>
#Html.DisplayNameFor(model => model.GeneCode)
</th>
<th>
#Html.DisplayNameFor(model => model.GeneName)
</th>
<th>
#Html.DisplayNameFor(model => model.GeneComments)
</th>
<th>
#Html.DisplayNameFor(model => model.WildType)
</th>
<th>
#Html.DisplayNameFor(model => model.WildTypeAllele)
</th>
<th>
#Html.DisplayNameFor(model => model.AtRiskAllele)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.GeneCode)
</td>
<td>
#Html.DisplayFor(modelItem => item.GeneName)
</td>
<td>
#Html.DisplayFor(modelItem => item.GeneComments)
</td>
<td>
#Html.DisplayFor(modelItem => item.WildType)
</td>
<td>
#Html.DisplayFor(modelItem => item.WildTypeAllele)
</td>
<td>
#Html.DisplayFor(modelItem => item.AtRiskAllele)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { }) |
#Html.ActionLink("Details", "Details", new { }) |
#Html.ActionLink("Delete", "Delete", new { })
</td>
</tr>
}
</table>
You should do it like that:
Model:
public class ModelB
{
public int Age { get; set; }
public string Name { get; set; }
}
Controller:
public ActionResult MyAction()
{
var model = new List<ModelB>
{
new ModelB{Age = 2, Name = "Bob"},
new ModelB{Age = 7, Name = "Sam"},
};
return View(model);
}
[HttpPost]
public ActionResult MyAction(List<ModelB> model)
{
//whatever
}
View:
#model List<TestWebApplication.Models.ModelB>
...
#using (Html.BeginForm())
{
for (int i = 0; i < Model.Count; i++)
{
Age: #Html.EditorFor(modelItem => Model[i].Age);
Name: #Html.EditorFor(modelItem => Model[i].Name);
<br />
}
<input type="submit"/>
}
Please note that I used for instead of foreach. When you populate a form you shouldn't use foreach - it will not render well.

Categories

Resources