MVC3 Binding to collection data model - asp.net-mvc-3

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"/>
}

Related

.Net MVC ModelState.IsValid always returns true

ModelState.IsValid is always returning true.
Code:
user.cs
public class User
{
public int UserID { get; set; }
public string Username { get; set; }
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
}
HomeController.cs
public ActionResult SaveUser(User user)
{
if (ModelState.IsValid)
{
//create DBContext object
using (var dbCtx = new UsersDbEntities())
{
dbCtx.Entry(user).State = EntityState.Modified;
dbCtx.SaveChanges();
}
return View("ShowUser", user);
}
return View("EditUser", user);
}
Register.cshtml
#model TrainingWebsite.Models.User
<div id="myForm">
#using (Html.BeginForm("RegisterUser", "Home", FormMethod.Post))
{
if (#ViewBag.Message != null)
{
<div style="border: 1px solid red">
#ViewBag.Message
</div>
}
<table>
<tr>
<td>#Html.LabelFor(a => a.Username)</td>
<td>#Html.TextBoxFor(a => a.Username, new { id = "id_username" })</td>
<td>#Html.ValidationMessageFor(a => a.Username)</td>
</tr>
<tr>
<td>#Html.LabelFor(a => a.FirstName)</td>
<td>#Html.TextBoxFor(a => a.FirstName, new { id = "id_firstName" })</td>
<td>#Html.ValidationMessageFor(a => a.FirstName)</td>
</tr>
<tr>
<td>#Html.LabelFor(a => a.LastName)</td>
<td>#Html.TextBoxFor(a => a.LastName, new { id = "id_lastName" })</td>
<td>#Html.ValidationMessageFor(a => a.LastName)</td>
</tr>
</table>
ModelState.IsValid is true even though Last Name field is empty yet is a required field
Any help would be appreciated. Thanks in advance
David

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>
}

Posted ViewModel return null properties

I am having issues with a view model that constantly return null properties after a post. Below is my code (it could be a syntax issue or two calling a class or property the same name as i saw in other posts but i could not see any such issue in code):
VIEW MODEL:
public class ProductItem
{
public int ProductID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string LongDescription { get; set; }
public int SupplierID { get; set; }
public string Dimensions { get; set; }
public double Price { get; set; }
public bool On_Sale { get; set; }
public double DiscountedPrice { get; set; }
public string Thumbnail { get; set; }
public string LargeImage { get; set; }
public string LargeImage2 { get; set; }
public string LargeImage3 { get; set; }
public string CrossRef { get; set; }
public byte Available { get; set; }
public double Weight { get; set; }
public byte Important { get; set; }
public virtual ICollection<ProductCategory> ProductCategories { get; set; }
// this is required on the page to allow products to be marked for deletion
public bool IsForDelete { get; set; }
}
public class ProductListViewModel
{
public IEnumerable<ProductItem> ProductItems { get; set; }
public IEnumerable<Category> CategoryItems { get; set; }
}
CONTROLLER:
public ActionResult ProductList()
{
var productList = new ProductListViewModel();
productList.ProductItems = productRepository.GetProductsWithDeleteOption().ToList();
productList.CategoryItems = categoryRepository.GetCategories().ToList();
return View(productList);
}
[HttpPost]
public ActionResult ProductList(ProductListViewModel productViewModel, FormCollection formCollection, string submit)
{
if (ModelState.IsValid)
{
// Check for submit action
if (submit == "Change Sort")
{
if (formCollection["Sortby"] == "ProductID")
{
OrderBy(productViewModel, formCollection, "m.ProductID");
}
else if (formCollection["Sortby"] == "Code")
{
OrderBy(productViewModel, formCollection, "m.Code");
}
else if (formCollection["Sortby"] == "Name")
{
OrderBy(productViewModel, formCollection, "m.Name");
}
else if (formCollection["Sortby"] == "Price")
{
OrderBy(productViewModel, formCollection, "m.Price");
}
}
else if (submit == "Delete all selected")
{
}
else if (submit == "Update All")
{
}
else if (submit == "Restrict Display")
{
}
}
return View(productViewModel);
}
VIEW:
#model Admin.Models.ViewModels.ProductListViewModel
#{
ViewBag.Title = "View Products";
}
#using (Html.BeginForm())
{
<h2>Product List as at #DateTime.Now.ToString("dd/MM/yyyy")</h2>
<table>
<tr>
<td>Sort by:</td>
<td>
<select name="Sortby">
<option value="ProductID">ProductID</option>
<option value="Code">Code</option>
<option value="Name">Name</option>
<option value="Price">Price</option>
</select>
</td>
<td>
<input type="radio" name="sortDirection" checked="checked" value="Asc" /> Ascending
<input type="radio" name="sortDirection" value="Desc" /> Descending
</td>
<td>
<input type="submit" name="submit" value="Change Sort" />
</td>
</tr>
<tr>
<td>Display only : (category)</td>
<td>#Html.DropDownList("CategoryID", new SelectList(Model.CategoryItems, "CategoryID", "Name"), "All Categories")</td>
<td colspan="2"><input type="submit" name="submit" value="Restrict Display" /></td>
</tr>
<tr>
<td colspan="4"><br />Total Number of products: #Model.ProductItems.Count()</td>
</tr>
</table>
<table>
<tr>
<th>
Edit
</th>
<th>
Code
</th>
<th>
Name
</th>
<th>
Price
</th>
<th>
On_Sale
</th>
<th>
DiscountedPrice
</th>
<th>
Weight
</th>
<th>
Delete
</th>
<th></th>
</tr>
#for (var i = 0; i < Model.ProductItems.ToList().Count; i++)
{
<tr>
<td>
#Html.HiddenFor(m => m.ProductItems.ToList()[i].ProductID)
#Html.ActionLink(Model.ProductItems.ToList()[i].ProductID.ToString(), "ProductEdit", new { id = Model.ProductItems.ToList()[i].ProductID })
</td>
<td>
#Html.DisplayFor(m => m.ProductItems.ToList()[i].Code)
</td>
<td>
#Html.DisplayFor(m => m.ProductItems.ToList()[i].Name)
</td>
<td>
#Html.EditorFor(m => m.ProductItems.ToList()[i].Price)
</td>
<td>
#Html.CheckBoxFor(m => m.ProductItems.ToList()[i].On_Sale, new { id = "On_Sale_" + Model.ProductItems.ToList()[i].ProductID })
</td>
<td>
#Html.EditorFor(m => m.ProductItems.ToList()[i].DiscountedPrice)
</td>
<td>
#Html.EditorFor(m => m.ProductItems.ToList()[i].Weight)
</td>
<td>
#Html.CheckBoxFor(m => m.ProductItems.ToList()[i].IsForDelete, new { id = Model.ProductItems.ToList()[i].ProductID })
</td>
<td>
#Html.ActionLink("Edit", "ProductEdit", new { id = Model.ProductItems.ToList()[i].ProductID }) |
#Html.ActionLink("Details", "Details", new { id = Model.ProductItems.ToList()[i].ProductID }) |
#Html.ActionLink("Delete", "Delete", new { id = Model.ProductItems.ToList()[i].ProductID })
</td>
</tr>
}
</table>
<p>
<input name="submit" type="submit" value="Delete all selected" />
</p>
<p>
<input name="submit" type="submit" value="Update All" />
</p>
<p>
#Html.ActionLink("Add a new product", "ProductAdd")
</p>
}
In the post action, the productViewModel argument has the ProductItems and CategoryItems properties as null.
Ok, so there are two problems.
I don't understand why you want to post list of the CategoryItems You should only expect the selected category and not the list
The problem with ProductItems is the name generated for <input> tags. Currently, the name being generated is name="[0].Price" whereas it should have been name="ProductItems[0].Price"
I changed the following code
#Html.EditorFor(m => m.ProductItems.ToList()[i].Price)
to
#Html.EditorFor(m => m.ProductItems[i].Price)
and it worked.
Note: I changed IEnumerable<ProductItem> ProductItems to List<ProductItem> ProductItems in ProductListViewModel
Yes it will be null on post back. I have a similar table in one of my projects and this is what I would have done given my situation.
You could change your view model to look like this then you don't have to do so many converting to lists in your view:
public class ProductListViewModel
{
public List<ProductItem> ProductItems { get; set; }
public List<Category> CategoryItems { get; set; }
}
Now in you view it could look something like this (this is just part of it, then rest you can just go and add):
#for (int i = 0; i < Model.ProductItems.Count(); i++)
{
<tr>
<td>
#Html.DisplayFor(m => m.ProductItems[i].Name)
#Html.HiddenFor(m => m.ProductItems[i].Name)
</td>
</tr>
<tr>
<td>
#Html.CheckBoxFor(m => m.ProductItems[i].IsForDelete)
</td>
</tr>
}
Add the code and do some debugging to see how the values are returned on submit
I hope this helps.

View to Controller in mvc3

I have a problem on passing values from view to controller
Here is my view:
#model IEnumerable<SQLOperation.Models.QuestionClass.Tabelfields>
#{
ViewBag.Title = "Question";
}
<h3> Question</h3>
#{int i = 0;}
#foreach (var item in Model)
{
using (Html.BeginForm("Question", "Home"))
{
#Html.DisplayFor(modelItem => item.QuestionName)
#Html.HiddenFor(m => item.QuestionID)
<br /><br />
if (item.Option1 != "")
{
#Html.RadioButtonFor(m => item.SelectedOption, item.Option1, item)
#Html.DisplayFor(modelItem => item.Option1)
<br /><br />
}
if (item.Option2 != "")
{
#Html.RadioButtonFor(m => item.SelectedOption, item.Option2, item)
#Html.DisplayFor(modelItem => item.Option2)
<br /><br />
}
if (item.Option3 != "")
{
#Html.RadioButtonFor(m => item.SelectedOption, item.Option3, item)
#Html.DisplayFor(modelItem => item.Option3)
<br /><br />
}
if (item.Option4 != "")
{
#Html.RadioButtonFor(m => item.SelectedOption, item.Option4, item)
#Html.DisplayFor(modelItem => item.Option4)
<br /><br />
}
i = (Int16)i + 1;
if (Model.Count() == i)
{
<input name="btnsumbit" type="submit" value="Submit Feedback"
style="font-family:Segoe UI Light;font-size:medium;"/>
}
}
}
My controller :
[HttpGet]
public ActionResult Question(string email)
{
var tf = new QuestionClass.Tabelfields();
IList<QuestionClass.Tabelfields> viewmodel = new List<QuestionClass.Tabelfields>();
var q = QuestionClass.getallQuestion(email).ToList();
foreach (SQLOperation.Models.Question item in q)
{
QuestionClass.Tabelfields viewItem = new QuestionClass.Tabelfields();
viewItem.Email = item.Email;
viewItem.QuestionID = item.QuestionID;
viewItem.QuestionName = item.QuestionName;
viewItem.Option1 = item.Option1;
viewItem.Option2 = item.Option2;
viewItem.Option3 = item.Option3;
viewItem.Option4 = item.Option4;
viewmodel.Add(viewItem);
}
return View(viewmodel);
}
[HttpPost, ActionName("Question")]
public void Question(IEnumerable<QuestionClass.Tabelfields> items)
{
}
My Model:
public class QuestionClass
{
public static FeedbackDatabaseDataContext context = new FeedbackDatabaseDataContext();
public class Tabelfields : Question
{
//public decimal QuestionID { get; set; }
//public string Email { get; set; }
//public string QuestionName { get; set; }
//public string Option1 { get; set; }
//public string Option2 { get; set; }
//public string Option3 { get; set; }
//public string Option4 { get; set; }
public string SelectedOption { get; set; }
}
public static List<Question> getallQuestion(string email)
{
var list = (from q in context.Questions where q.Email == #email select q);
return list.ToList();
}
}
however I get NULL in "items" in controller.
[HttpPost, ActionName("Question")]
public void Question(IEnumerable<QuestionClass.Tabelfields> items)
{
}
Whereas if I change my View & Controller to below , I get last value from database in controller
View:
#foreach (var item in Model)
{
using (Html.BeginForm("Question", "home", new { email=item.Email, q=item.QuestionID}))
{
#Html.DisplayFor(modelItem => item.QuestionName)
#Html.HiddenFor(m => item.QuestionID)
.
.
.
.
}
}
Controller:
[HttpPost, ActionName("Question")]
public void Question(string email,int q)
{
}
I get values in email and q
so how can I get all values i.e. QuestionId,Email,Questionname and it's appropriate selected value (radiobutton) in controller ?
i.e. in Following Controller:
[HttpPost, ActionName("Question")]
public void Question(IEnumerable<QuestionClass.Tabelfields> items)
{
}
You need to index the Html.*For items as such;
#Html.RadioButtonFor(m => m[i].SelectedOption, item.Option3, item)
To make things simplier, i'd probably get rid of the foreach & and separate i declaration and use the following;
#for(int i=0; i < Model.Count; i++)
{
#Html.HiddenFor(m => m[i].QuestionID)
#Html.RadioButtonFor(m => m[i].SelectedOption, Model[i].Option3, Model[i])
}
etc.
Indexing like this will cause the html to be rendered with the indexing intact:
<input type='hidden' name=[0].'QuestionId' />
<input type='hidden' name=[1].'QuestionId' />
<input type='hidden' name=[2].'QuestionId' />
Rather than what you're doing currently, which ends up rendering as so;
<input type='hidden' name='QuestionId' />
<input type='hidden' name='QuestionId' />
<input type='hidden' name='QuestionId' />
Without the indexing, each form field is given the same name, so you're controller is going to think only one was returned.

To get the value of check boxes from a list of dynamicallly created check boxes in razor view engine

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>

Resources