To get the value of check boxes from a list of dynamicallly created check boxes in razor view engine - asp.net-mvc-3

How to find the values of checkboxes(i.e., whether checked or not) from a list of dynamically created check boxes in razor view engine? the code runs as follows...
#foreach (var item in Model))
{
<tr>
<td class="Viewtd">
#Html.ActionLink(item.Title, "Edit", new { id = item.id})
</td>
<td>
#Html.CheckBox("ChkBox"+item.ThresholdID , false, new { id = item.id})
</td>
</tr>
}
How to get those check boxes values in the controller?

Do it the proper way: using view models and editor templates.
As always start by defining a view model:
public class MyViewModel
{
public string Title { get; set; }
public string Id { get; set; }
public bool IsThreshold { get; set; }
}
then a controller to populate this view model :
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new[]
{
new MyViewModel
{
Id = "1",
Title = "title 1",
IsThreshold = false,
},
new MyViewModel
{
Id = "2",
Title = "title 2",
IsThreshold = true,
},
new MyViewModel
{
Id = "3",
Title = "title 3",
IsThreshold = false,
},
};
return View(model);
}
[HttpPost]
public ActionResult Edit(MyViewModel model)
{
// This action will be responsible for editing a single row
// it will be passed the id of the model and the value of the checkbox
// So here you can process them and return some view
return Content("thanks for updating", "text/plain");
}
}
and then the Index view (~/Views/Home/Index.cshtml):
#model IEnumerable<MyViewModel>
<table>
<thead>
<tr>
<th></th>
<th>Threshold</th>
</tr>
</thead>
<tbody>
#Html.EditorForModel()
</tbody>
</table>
and finally the editor template (~/Views/Home/EditorTemplates/MyViewModel.cshtml):
#model MyViewModel
#{
ViewData.TemplateInfo.HtmlFieldPrefix = "";
}
<tr>
#using (Html.BeginForm("Edit", "Home"))
{
#Html.HiddenFor(x => x.Id)
#Html.HiddenFor(x => x.Title)
<td><input type="submit" value="#Model.Title" /></td>
<td>#Html.CheckBoxFor(x => x.IsThreshold)</td>
}
</tr>

Related

.NET Core 6 Pull Down Menu Selection to Group through View Model

I am having partial success searching / grouping data through a viewmodel:
Partial Success:
URL Value
If I search on "B"
https://localhost:7207/Class01Name/Index2?String02NameSelected=B&SearchString=
Problem:
Not filtering data...simply changes pull down menu back to "All," displaying all data. Data not filtered.
**Question:
**
What in the code has to be changed to have the data filtered successfully?
Question is based on Tutorial at:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/search?view=aspnetcore-6.0
Model
using System.ComponentModel.DataAnnotations; // Date Format
namespace Project01Name.Models
{
public class Class01Name
{
public int Id { get; set; }
public string? String01Name { get; set; }
public string? String02Name { get; set; }
public int? Int01Name { get; set; }
public bool? Bool01Name { get; set; }
[DataType(DataType.Date)]
public DateTime? DateTime01Name { get; set; }
}
}
**
View Model
**
using Microsoft.AspNetCore.Mvc.Rendering;
using System.Collections.Generic;
namespace Project01Name.Models.ViewModelsName
{
public class SearchByGroupName
{
public List<Class01Name>? Class01NameList { get; set; } // A list of movies.
public SelectList? String02NameSelection { get; set; } // A SelectList containing the list of genres. This allows the user to select a genre from the list.
public string? String02NameSelected { get; set; } // MovieGenre, which contains the selected genre.
public string? SearchString { get; set; } // SearchString, which contains the text users enter in the search text box.
}
}
Controller Action Method
// GET: String01Names
public async Task<IActionResult> Index2(string class01NameGroup, string searchString)
{
// Use LINQ to get list of genres.
IQueryable<string> string02NameQuery = from m in _context.Class01Name
orderby m.String02Name
select m.String02Name;
var selectVariable = from m in _context.Class01Name
select m;
if (!string.IsNullOrEmpty(searchString))
{
selectVariable = selectVariable.Where(s => s.String01Name!.Contains(searchString));
}
if (!string.IsNullOrEmpty(class01NameGroup))
{
selectVariable = selectVariable.Where(x => x.String02Name == class01NameGroup);
}
var string02NameVM = new SearchByGroupName
{
String02NameSelection = new SelectList(await string02NameQuery.Distinct().ToListAsync()),
Class01NameList = await selectVariable.ToListAsync()
};
return View(string02NameVM);
}
View
#model Project01Name.Models.ViewModelsName.SearchByGroupName
#{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<p>
<a asp-action="Create">Create New</a>
</p>
<form asp-action="Index2" method="get">
<div class="form-actions no-color">
<p>
<select asp-for="String02NameSelected" asp-items="Model.String02NameSelection"> <option value="">All</option></select>
Title: <input type="text" asp-for="SearchString" />
<input type="submit" value="Filter" />
#*<input type="submit" value="Search" class="btn btn-default" /> |
<a asp-action="Index">Back to Full List</a> *#
</p>
</div>
</form>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String02Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].Int01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].DateTime01Name)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Class01NameList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.String01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.String02Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Int01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateTime01Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
Partial Success:
URL Value
If I search on "B"
https://localhost:7207/Class01Name/Index2?String02NameSelected=B&SearchString=
Problem:
Not filtering data...simply changes pull down menu back to "All," displaying all data. Data not filtered.
**Question:
**
What in the code has to be changed to have the data filtered successfully?
Question is based on Tutorial at:
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-mvc-app/search?view=aspnetcore-6.0
Not filtering data...simply changes pull down menu back to "All,"
displaying all data. Data not filtered.
**Question: ** What in the code has to be changed to have the data filtered successfully?
Well, seems you wanted to implement searching functionality in way, so that you can filter with the dropdown and search box and finally if you select All as dropdown value you want to load all the list without any filter and shorting means the full list which comes at first view.
If so, you need to use javascript for your dropdown change event as cshtml doesn't deal with change event. In addition, as you are using asp.net core MVC which would return HTML View altough, we need json data for Ajax reponse but we are would bee getting HTML View. So Ajax success Function will through an error where we would use filter with All parameter.
Modification Required:
Javascript:
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("#allId").change(function () {
alert("Click");
var allId = $('#allId').val();
console.log(allId);
if (allId == "All") {
alert("Alert");
$.ajax({
url: 'http://localhost:5094/Search/Index2',
type: 'GET',
dataType: 'json',
data: { String02NameSelected: "All", searchString: "" },
success: function (response) {
},
error: function () {
window.location.href = "#Url.Action("Index2", "Search")?String02NameSelected=All&SearchString=";
}
});
}
});
});
</script>
}
Note:
As you can see, in success function we are doing nothing, because it will always throuh an error because we are not returning json. Thus, we will work in error section. indow.location.href = "#Url.Action("Index2", "Search")?String02NameSelected=All&SearchString=";. Here, for your understanding, we will call this function when we select All as our dropdown value in that scenario, we will pass All and nothing , nothing will convert into null and all will be our search key.
Modify Your Existing View:
In your existing view, replace blow dropdown code snippet , means the select items
<select asp-for="String02NameSelected" id="allId" asp-items="Model.String02NameSelection"> <option value="All">All</option></select>
Note: If you notice I hav introduced a id id="allId" which will be using on dropdown change event.
Controller:
public async Task<IActionResult> Index2(string String02NameSelected, string searchString)
{
if (String02NameSelected == "All" && searchString == null)
{
var dataWithoutfileter = new SearchByGroupName();
dataWithoutfileter.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
dataWithoutfileter.Class01NameList = listOfClass01Name;
return View(dataWithoutfileter);
}
if (!String.IsNullOrEmpty(String02NameSelected) && String02NameSelected !="All")
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(String02NameSelected.ToLower()) || m.String02Name.ToLower().Contains(String02NameSelected.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
if (!String.IsNullOrEmpty(searchString))
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(searchString.ToLower()) || m.String02Name.ToLower().Contains(searchString.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
//First loading
var objSearchByGroupName = new SearchByGroupName();
objSearchByGroupName.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
objSearchByGroupName.Class01NameList = listOfClass01Name;
return View(objSearchByGroupName);
}
}
Complete Demo:
Full Controller With Seed Model Class Value:
public class SearchController : Controller
{
public static List<Class01Name> listOfClass01Name = new List<Class01Name>()
{
new Class01Name() { Id =101, String01Name ="Titanic",String02Name = "Romantic", Int01Name =01, Bool01Name = false, DateTime01Name = new DateTime(2023-01-15) },
new Class01Name() { Id =102, String01Name ="Forest gump",String02Name = "Motivational", Int01Name =02, Bool01Name = true, DateTime01Name = new DateTime(2023-01-12) },
new Class01Name() { Id =103, String01Name ="Spider Man",String02Name = "Action", Int01Name =03, Bool01Name = false, DateTime01Name = new DateTime(2023-01-10) },
new Class01Name() { Id =104, String01Name ="Harry Potter",String02Name = "Suspense", Int01Name =04, Bool01Name = true, DateTime01Name = new DateTime(2023-01-13)},
};
public List<SelectListItem> String02NameSelectionList = new List<SelectListItem>()
{
new SelectListItem { Text = "Motivational", Value = "Motivational" },
new SelectListItem { Text = "Romantic", Value = "Romantic" },
new SelectListItem { Text = "Action", Value = "Action" },
new SelectListItem { Text = "Comedy", Value = "Comedy" }
};
public async Task<IActionResult> Index2(string String02NameSelected, string searchString)
{
if (String02NameSelected == "All" && searchString == null)
{
var dataWithoutfileter = new SearchByGroupName();
dataWithoutfileter.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
dataWithoutfileter.Class01NameList = listOfClass01Name;
return View(dataWithoutfileter);
}
if (!String.IsNullOrEmpty(String02NameSelected) && String02NameSelected !="All")
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(String02NameSelected.ToLower()) || m.String02Name.ToLower().Contains(String02NameSelected.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
if (!String.IsNullOrEmpty(searchString))
{
var objOfClass = new SearchByGroupName();
var string02NameQuery = listOfClass01Name.Where(m => m.String01Name.ToLower().Contains(searchString.ToLower()) || m.String02Name.ToLower().Contains(searchString.ToLower()));
objOfClass.Class01NameList = string02NameQuery.ToList();
objOfClass.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
return View(objOfClass);
}
//First loading
var objSearchByGroupName = new SearchByGroupName();
objSearchByGroupName.String02NameSelection = new SelectList(String02NameSelectionList, "Text", "Value");
objSearchByGroupName.Class01NameList = listOfClass01Name;
return View(objSearchByGroupName);
}
}
Full View:
#model DotNet6MVCWebApp.Controllers.SearchByGroupName
#{
ViewData["Title"] = "Index";
}
<form asp-action="Index2" method="get">
<div class="form-actions no-color">
<p>
<select asp-for="String02NameSelected" id="allId" asp-items="Model.String02NameSelection"> <option value="All">All</option></select>
Title: <input type="text" asp-for="SearchString" />
<input type="submit" name="searchString" />
</p>
</div>
</form>
<table class="table">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].String02Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].Int01Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Class01NameList[0].DateTime01Name)
</th>
<th></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Class01NameList)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.String01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.String02Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Int01Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.DateTime01Name)
</td>
<td>
<a asp-action="Edit" asp-route-id="#item.Id">Edit</a> |
<a asp-action="Details" asp-route-id="#item.Id">Details</a> |
<a asp-action="Delete" asp-route-id="#item.Id">Delete</a>
</td>
</tr>
}
</tbody>
</table>
#section scripts {
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function () {
$("#allId").change(function () {
alert("Click");
var allId = $('#allId').val();
console.log(allId);
if (allId == "All") {
alert("Alert");
$.ajax({
url: 'http://localhost:5094/Search/Index2',
type: 'GET',
dataType: 'json',
data: { String02NameSelected: "All", searchString: "" },
success: function (response) {
},
error: function () {
window.location.href = "#Url.Action("Index2", "Search")?String02NameSelected=All&SearchString=";
}
});
}
});
});
</script>
}
Output:

ASP.NET Core 6 MVC : HTML table to view model collection

Starting up with ASP.NET Core 6 MVC and in my case I have one view which lists few properties of one object and then some other for their children in a editable table (user can edit the values)
View model has the properties and an IEnumerable of the children:
public class MyObjectViewModel
{
public String Id { get; set; }
public String Descr { get; set; }
public IEnumerable<ChildrenObject> Children { get; set; }
public MyObjectViewModel()
{
Children = Enumerable.Empty<ChildrenObject>();
}
public class ChildrenObject
{
public String? Id { get; set; }
public String? Name { get; set; }
}
}
All under the same form:
#using (Html.BeginForm("Save", "Controller", FormMethod.Post))
{
<input type="submit" value="SAVE"/>
<br />
#Html.LabelFor(model => model.Id)
#Html.TextBoxFor(model => model.Id, new { #readonly = "readonly" })
<br />
#Html.LabelFor(model => model.Descr)
#Html.EditorFor(model => model.Descr)
<br />
<table>
<tbody>
<tr>
<th>Id</th>
<th>Name</th>
</tr>
#foreach (var child in Model.Children)
{
<tr>
<td>#child.Id</td>
<td><input class="ef-select" type="text" value="#child.Name"></td>
</tr>
}
</tbody>
</table>
}
So when the button is pressed the data is dumped back to the model to perform the SAVE action in the controller.
All ok for the simple fields (I can get the data in the controller as the view model), but not sure how to accomplish it with the table / children property...
Any simple way without needing to use JS to serialise or pick up the data from the table?
Thanks
If you want to pass id and name of ChildrenObject in table,you can try to add hidden inputs for the Id,and set name attribute for name inputs:
#{var count = 0; }
#foreach (var child in Model.Children)
{
<tr>
<td>
#child.Id
<input value="#child.Id" name="Children[#count].Id" />
</td>
<td><input class="ef-select" type="text" value="#child.Name" name="Children[#count].Name"></td>
</tr>
count++;
}

MVC4 How to get the data in partial view when parent view click submit

MVC4 How to get the data in partial view when parent view click submit
I create a edit page for user update the data, the parent view show some of book details and partial view is a loop show the status of each book. Also, the parent view have a submit button for update both of partial view and parent view, but when I click the submit only parent view data can update and partial view still not update. The code below:
Model:
public class LibraryInventory
{
public decimal LibraryID { get; set; }
public string Title { get; set; }
public List<LibraryItem> Entities { get; set; }
}
public class LibraryItem
{ public decimal StatusID { get; set; }
public string Location { get; set; }
public decimal BorrowedBy { get; set; }
}
Controller :
public ActionResult EditRecord(string ID)
{
DataTable dt = (DataTable)Session["EditGridData"];
LibraryInventory record = new LibraryInventory(dt.Rows[0]);
dt = LibraryEditBLL.GetEditItems(ID);
if (results.ToList().Count > 0)
{
record.Entities = LibraryItem.ConvertToLibraryEntity(dt).ToList();
}
return View(record);
}
[HttpPost]
public ActionResult EditRecord(string FormButton, LibraryInventory model)
{
switch (FormButton)
{
case "Submit":
if (ModelState.IsValid)
{
LibraryEditBLL.UpdateInventoryLibrary(model);
}
return View("EditRecord",record);
default:
return RedirectToAction("Edit"); //other page not need check
}
View :
#model XXX.Models.LibraryModels.LibraryInventory
#using (Html.BeginForm("EditRecord", "Library", FormMethod.Post, new { enctype = "multipart/form-data" })){
#Html.HiddenFor(m =>m.LibraryID)
<table>
<tr>
<td>#Html.TextBoxFor(m => m.Title)</td>
#for (var i = 0; i < #Model.Entities.Count; i++)
{
#Html.Partial("EditItem", #Model.Entities[i])
}
</tr>
</table>
}
#model XXX.Models.LibraryModels.LibraryItem
<tr>
<td> #Html.DropDownListFor(m => m.StatusID) </td>
<td> #Html.DropDownListFor(m => m.Location)</td>
<td> #Html.DropDownListFor(m => m.BorrowedBy) </td>
</tr>
Try this code for your view. And no need of partialview for this simple scenario.
#model XXX.Models.LibraryModels.LibraryInventory
#using (Html.BeginForm("EditRecord", "Library", FormMethod.Post, new { enctype = "multipart/form-data" })){
#Html.HiddenFor(m =>m.LibraryID)
<table>
<tr>
<td>#Html.TextBoxFor(m => m.Title)</td>
</tr>
#for (var i = 0; i < Model.Entities.Count; i++)
{
<tr>
<td> #Html.DropDownListFor(m => Model.Entities[i].StatusID) </td>
<td> #Html.DropDownListFor(m => Model.Entities[i].Location)</td>
<td> #Html.DropDownListFor(m => Model.Entities[i].BorrowedBy) </td>
</tr>
}
</table>
}

How to verify which checbox is checked in the view in MVC3?

Model :
public IEnumerable<Role> Roles { get; set; }
Index :
Roles = securityServiceClient.GetAllRoles()
View :
#foreach (var role in Model.Roles)
{
<tr>
#if (role.Name == "User")
{
<td><input type="checkbox" checked="checked"/></td>
}
else
{
<td><input type="checkbox"/></td>
}
<td>#Html.Label(role.Name)</td>
</tr>
}
[HttpPost]
CreateSomething :
How can I get the selected checkbox(s) from the view?
You must give your checkboxes names:
#if (role.Name == "User")
{
<td><input type="checkbox" checked="checked" name="roles"/></td>
}
else
{
<td><input type="checkbox" name="roles"/></td>
}
and then:
[HttpPost]
public ActionResult Index(IEnumerable<string> roles)
{
...
}
Also you should be using view models, strongly typed views and helpers and not hardcode checkboxes as you did in your veiws.
Here's what I mean:
Model:
public class MyViewModel
{
public RoleViewModel[] Roles { get; set; }
}
public class RoleViewModel
{
public string RoleName { get; set; }
public bool IsSelected { get; set; }
}
and then:
public class HomeController: Controller
{
public ActionResult Index()
{
var roles = securityServiceClient.GetAllRoles().Select(r => new RoleViewModel
{
RoleName = r.Name
});
var model = new MyViewModel
{
Roles = roles
};
return View(model);
}
[HttpPost]
public ActionResult Index(IEnumerable<RolesViewModel> roles)
{
...
}
}
and in the view:
#model MyViewModel
#using (Html.BeginForm())
{
<table>
<thead>
<tr>
<th>role</th>
</tr>
</thead>
<tbody>
#for (var i = 0; i < Model.Roles.Length; i++)
{
<tr>
<td>
#Html.CheckBoxFor(x => x.Roles[i].IsSelected)
#Html.LabelFor(x => x.Roles[i].IsSelected, Model.Roles[i].RoleName)
#Html.HiddenFor(x => x.Roles[i].RoleName)
</td>
</tr>
}
</tbody>
</table>
}

MVC3 Binding to collection data model

My question isn't so much about displaying the data its about collecting changes to the data.
My specific scenario is the need to allow users to delete multiple items from a list. I don't know if i'm even approaching this in a locgical way.
The List is a collection of Private Messages. My view model has strings for To, From, Subject, and a bool for "Delete".
public class PrivateMessagesModel {
public PrivateMessagesModel()
{
PrivateMessages = new List<PrivateMessageReceivedModel>();
}
public List<PrivateMessageReceivedModel> PrivateMessages;
}
public class PrivateMessageReceivedModel
{
[DataType(DataType.Text)]
[Display(Name = "From")]
public string From { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Subject")]
public string Subject { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Message")]
public string Message { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Date")]
public DateTime DateTimeSent { get; set; }
[DataType(DataType.Text)]
[Display(Name = "Delete")]
public bool Delete { get; set; }
}
The code to display looks like this. And works ok.
#
model ScaleRailsOnline.Models.PrivateMessagesModel
#{
ViewBag.Title = "Private Messages";
}
<div id="content">
<div class="content">
<h2>
Private Messages</h2>
#using (Html.BeginForm())
{ <table>
#for (int i = 0; i < Model.PrivateMessages.Count; i++)
{
<tr>
<td>
#Html.CheckBoxFor(m => m.PrivateMessages[i].Delete)
</td>
<td>
#Html.DisplayTextFor(m => m.PrivateMessages[i].From)
</td>
</tr>
}
</table>
<p>
<input type="submit" value="Delete" />
</p>
}
</div>
</div>
The problem is when I check a couple of the check boxes and hit the delete button, i get nothing back in the model.
Again, im sure i'm not approaching this in the right way. Any help would be appreciated.
You need to have a controller associated to the Html.BeginForm where the form will be posted.
eg
<div id="formid">
#using (Html.BeginForm("Index1", "Home", new AjaxOptions { UpdateTargetId = "formid",OnSuccess ="OnSuccess" }, new { id = "TheForm" }))
{
#for (int i = 0; i < Model.PrivateMessages.Count; i++)
{
#Html.CheckBoxFor(m => m.PrivateMessages[i].Delete)
}
<input type="submit" name="name" value="Submit" />
}
</div>
On Controller
public ActionResult Index1(List<PrivateMessageReceivedModel> mod)
{
//Now in the mod you will get the value of the delete checkbox.
}
You have to create a Controller class for your model. Then create method that return ActionResult type. and then create View of the newly created controller method.
Here is a sample code.
Model Class
namespace Mvc3Application1.Models
{
public class PrivateMessage
{
public string From { get; set; }
public string Subject { get; set; }
public string Message { get; set; }
public DateTime DateTimeSent { get; set; }
public bool Delete { get; set; }
}
public class PrivateMessageRepository
{
public List<PrivateMessage> GetPrivateMessages()
{
List<PrivateMessage> myPrivateMessages=new List<PrivateMessage>();
//add list of messages in the object myPrivateMessages
myPrivateMessages.Add(new PrivateMessage { From = "abc#abc.com", Subject = "Subject 1", Message = "Message 1", DateTimeSent = DateTime.Now, Delete = false });
myPrivateMessages.Add(new PrivateMessage { From = "abc1#abc.com", Subject = "Subject 2", Message = "Message 2", DateTimeSent = DateTime.Now, Delete = false });
myPrivateMessages.Add(new PrivateMessage { From = "abc2#abc.com", Subject = "Subject 3", Message = "Message 3", DateTimeSent = DateTime.Now, Delete = false });
myPrivateMessages.Add(new PrivateMessage { From = "abc3#abc.com", Subject = "Subject 4", Message = "Message 4", DateTimeSent = DateTime.Now, Delete = false });
myPrivateMessages.Add(new PrivateMessage { From = "abc4#abc.com", Subject = "Subject 5", Message = "Message 5", DateTimeSent = DateTime.Now, Delete = false });
return myPrivateMessages;
}
}
}
Controller class
namespace Mvc3Application1.Controllers {
public class PrivateMessageController : Controller
{
//
// GET: /PrivateMessage/
// Show all the private messages
public ActionResult ListMessages()
{
return View(new Models.PrivateMessageRepository().GetPrivateMessages());
}
//delete the selected messages and return the collection
[HttpPost]
public ActionResult ListMessages(FormCollection collection)
{
List<Models.PrivateMessage> messages = new Models.PrivateMessageRepository().GetPrivateMessages();//all messages
List<Models.PrivateMessage> cloneMessages = new List<Models.PrivateMessage>();//messages left for deletion
int noOfItems = 0;//no of items deleted
int currentItem = 0;//current item in collection 'messages'
string[] deletedItems = collection[0].Split(',');//return from HTML control collection
for (int i = 0; i < deletedItems.Length; i++)
{
if (bool.Parse(deletedItems[i]) == false)//if checkbox is unchecked
{
cloneMessages.Add(messages[currentItem]);//copy original message in cloneMessages collection
}
else //if checkbox is checked
{
noOfItems++;
i++;
}
currentItem++;
}
ViewBag.Items = noOfItems + " message(s) deleted.";
return View(cloneMessages);
}
} }
View
#model IEnumerable<Mvc3Application1.Models.PrivateMessage>
#{
ViewBag.Title = "Private Messages";
}
<h2>Private Messages</h2>
<div style="color:green;font-weight:bold;">#ViewBag.Items</div>
<br />
#using (Html.BeginForm())
{
<table>
<tr>
<th></th>
<th>
From
</th>
<th>
Subject
</th>
<th>
Message
</th>
<th>
DateTimeSent
</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.CheckBoxFor(modelItem => item.Delete)
</td>
<td>
#Html.DisplayTextFor(modelItem => item.From)
</td>
<td>
#Html.DisplayTextFor(modelItem => item.Subject)
</td>
<td>
#Html.DisplayTextFor(modelItem => item.Message)
</td>
<td>
#Html.DisplayTextFor(modelItem => item.DateTimeSent)
</td>
</tr>
}
</table>
<input type="submit" value="Delete"/>
}

Resources