insert multiple row in a single form using ASP.NET MVC - asp.net-mvc

here my question is that where user enters area details like place-name, noofplaces, like that after creating user details here user entered noofplaces, so how many enters(10,20 or even 100) that many rows should be created.
here is the code worked for me
Area Model
`public class Area
{
[Key]
public int AreaID { get; set; }
public string ParkingPlaceName { get; set; }
public int NoOfParkingPlaces { get; set; }
[DataType(DataType.Currency)]
public decimal MinimumCharges { get; set; }
public string Address { get; set; }
[Precision(25,22)]
public decimal Latitude { get; set; }
[Precision(25,22)]
public decimal Longitude { get; set; }
public virtual ICollection<Car> Cars { get; set; }
public virtual ICollection<ParkingPlace> ParkingPlaces { get; set; }
}
}`
ParkingPlace Model
public class ParkingPlace
{
[Key]
public int ParkID { get; set; }
public string PlaceId { get; set; }
public int AreaID { get; set; }
public virtual ICollection<Car> Cars { get; set; }
public virtual Area Areas { get; set; }
}
controller code
public ActionResult Create(string areaName)
{
Area area = db.Areas.SingleOrDefault(x => x.ParkingPlaceName == areaName);
return View(area);
}
[HttpPost]
public ActionResult Create([Bind(Include = "ParkID,PlaceId,AreaID")] List<Place> place)
{
if (ModelState.IsValid)
{
foreach(var i in place)
{
db.Places.Add(i);
}
db.SaveChanges();
return RedirectToAction("Index", "Area");
}
return View(place);
}
View Code
#model CarParking.Models.Area
#using (Html.BeginForm("Create","ParkingPlace", FormMethod.Post))
{
<hr />
<table>
<tr>
<th>Place ID's</th>
<th>Area ID's</th>
</tr>
#for (int i = 0; i < Model.NoOfParkingPlaces; i++)
{
<tr class="form-group">
<td>
#Html.TextBox("[" + i + "].PlaceId", "P.Id_" + i + "", htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessage("[" + i + "].PlaceId", "", new { #class = "text-danger" })
</td>
<td>
#Html.TextBox("[" + i + "].AreaID", Model.AreaID, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessage("[" + i + "].AreaID", "", new { #class = "text-danger" })
</td>
<td>
#Html.Hidden("[" + i + "].PlaceId_Status", false)
#Html.ValidationMessage("[" + i +"].PlaceId_Status", "", new { #class = "text-danger"})
</td>
</tr>
}
</table>
<p>
<input type="submit" value="Create" class="btn btn-default" />
</p>
}

Related

ViewModel, View and PartialView Post to Controller

I am trying to do the following: I have two models, header and List(details), sent to a view by a view model. When loading the main view, a dropdown is displayed from a list in the ViewModel.header model previously loaded. When you click on that dropdown, a partial view is loaded with some values, filtered by the value of the ddl, of the ViewModel.List(details) for the user to complete the information. So far everything works fine, but when doing the Post, controller it receives the ViewModel.List(details) in null.
what am I doing wrong?
Header
public class StockTransactionsHeader
{
[Key]
public int TransactionHeaderID { get; set; }
public DateTime TransactionDate { get; set; }
public string TransactionDocument { get; set; }
public int CategoryID { get; set; }
[NotMapped]
public List<SelectList> CategoryCollection { get; set; }
public virtual List<StockTransactionsDetails> StockTransactionsDetails { get; set; }
}
Details
public class StockTransactionsDetails
{
[Key]
public int TransactionDetailID { get; set; }
public int TransactionHeaderID { get; set; }
public int ProductID { get; set; }
public decimal Qty { get; set; }
public decimal Amount { get; set; }
public decimal TransactionAmount { get; set; }
[NotMapped]
public string ProductDescription { get; set; }
public virtual StockTransactionsHeader StockTransactionsHeader { get; set; }
}
ViewModel
public class StockTransactionsViewModel
{
public StockTransactionsHeader StockTransactionsHeader { get; set; }
public List<StockTransactionsDetails> StockTransactionsDetails { get; set; }
}
Controller Create
public ActionResult Create()
{
var stockTransactions = new StockTransactionsViewModel();
stockTransactions.StockTransactionsHeader = GetHeaderCategories();
return View(stockTransactions);
}
GetHeaderCategories()
private StockTransactionsHeader GetHeaderCategories()
{
var header = new StockTransactionsHeader();
header.CategoryCollection = CommonServices.GetSelecList((int)DeliveryCommonHelper.ConfigurationType.Categoria);
return header;
}
MainView
#model DeliverySolutionCommon.ViewModels.StockTransactionsViewModel
#using (Html.BeginForm())
{
<div class="form-row">
<div id="partialView" class="table-responsive">
</div>
</div>
<div class="form-group">
<div class="col-md-2">
<input type="submit" value=" Procesar " class="btn btn-warning" />
</div>
</div>
}
Script to load partial view
<script>
$(document).ready(function () {
$("#Category").on("change", function () {
autoFiltro();
})
})
function autoFiltro() {
var url = "#Url.Action("GetProductsListByCategory", "StockTransactions")";
var id = $("#Category").val();
var data = { idCategory: id };
$.post(url, data).done(function (data) {
$("#partialView").html(data);
})
}
</script>
GetProductsListByCategory
[HttpPost]
public PartialViewResult GetProductsListByCategory(int idCategory)
{
var products = ProductsServices.GetProductsListByCategory(idCategory);
var stockTransactions = new StockTransactionsViewModel();
stockTransactions.StockTransactionsDetails = GetTransactionsDetails(products);
return PartialView("_createStockTransactions", stockTransactions);
}
GetTransactionsDetails
private List<StockTransactionsDetails> GetTransactionsDetails (List<Products> products)
{
var details = new List<StockTransactionsDetails>();
foreach (var item in products)
{
StockTransactionsDetails detail = new StockTransactionsDetails();
detail.ProductID = item.ProductID;
detail.ProductDescription = item.Description;
details.Add(detail);
}
return details;
}
PartialView
#model DeliverySolutionCommon.ViewModels.StockTransactionsViewModel
<table class="table table-sm table-bordered table-striped">
#foreach (var item in Model.StockTransactionsDetails)
{
<tr class="d-flex">
<td class="col-7">
#Html.DisplayFor(modelItem => item.ProductDescription)
</td>
<td class="col-1">
#Html.EditorFor(modelItem => item.Qty, new { htmlAttributes
= new { #class = "form-control" } })
</td>
<td class="col-2">
#Html.EditorFor(modelItem => item.Amount, new {
htmlAttributes = new { #class = "form-control" } })
</td>
<td class="col-2">
#Html.EditorFor(modelItem => item.TransactionAmount, new {
htmlAttributes = new { #class = "form-control" } })
</td>
</tr>
}
</table>
Aaaaand finally Create Post
[HttpPost]
public ActionResult Create(StockTransactionsViewModel stockTransactionsView)
{
// StockStransactionsView.StockTransactionsDetails = null
}
The problem is you are posting back a list and there is no indexing information in your HTML... MVC model binder does not know how to put the items in a list without the index info...
you can try something like this:
#for (int i = 0; i < Model.StockTransactionsDetails.Count, i++)
{
<tr class="d-flex">
<td class="col-7">
#Html.EditorFor(modelItem => Model[i].Amount, new {
htmlAttributes = new { #class = "form-control" } })
</td>
// more code...
This would add the indexing information to your HTML...
Alternatively you can use EditorTemplate... something like this:
// Note that EditorFor template would iterate the list item for you
#Html.EditorFor(m => m.Model.StockTransactionsDetails)
This tutorial might help

Pass Foreign Key via Post Form

I am doing an exercise of creating an helpdesk system. I'm using code first so i create some scripts that i'll describe briefly.
This class is my main class
public class Ticket
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
[Required]
[Display(Name = "Descrição")]
public string Description { get; set; }
public TicketStatus TicketStatus { get; set; }
public byte TicketStatusId { get; set; }
}
and i created this class to handle ticket answer with an fk to a ticket
public class TicketAnswer
{
public int Id { get; set; }
public Ticket Ticket { get; set; }
public int TicketId { get; set; }
public string Message { get; set; }
}
To create my form i created a viewmodel to handle all ticket answers
public class AnswerTicketViewModel
{
//public IEnumerable<TicketStatus> TicketStatus { get; set; }
public Ticket Ticket { get; set; }
public List<TicketAnswer> TicketAnswer { get; set; }
public string Message { get; set; }
}
and passing this form
#using (Html.BeginForm("SaveAnswer", "Ticket"))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(model => model.Ticket.Id)
<div class="form-group">
#Html.LabelFor(model => model.Message, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextAreaFor(model => model.Message, 10, 50, new { htmlAttributes = new { #readonly = "readonly", disabled = "disabled", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Message, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Enviar Resposta" class="btn btn-default" />
</div>
</div>
}
this is the action
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SaveAnswer(TicketAnswer ticket)
{
if (!ModelState.IsValid)
{
var ticketStatus = _context.TicketStatus.ToList();
var ticketAnswer = _context.TicketAnswer.Where(t => t.TicketId == ticket.Ticket.Id).ToList();
var viewModel = new AnswerTicketViewModel
{
Ticket = ticket.Ticket,
TicketAnswer = ticketAnswer
};
return View("AnswerTicketForm", viewModel);
}
_context.TicketAnswer.Add(ticket);
_context.SaveChanges();
return RedirectToAction("Index", "Ticket");
}
I'm getting an error "The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo_TicketAnswers_dbo_Tickets_TicketId" how i change that and handle this fk? I try all kinds of solution can someone give a tip?
Got it guys on my viewmodel i put a variable that i set on the form to the id of the ticket and it persists on the post method
public class AnswerTicketViewModel
{
//public IEnumerable<TicketStatus> TicketStatus { get; set; }
public Ticket Ticket { get; set; }
public int TicketId { get; set; }
public List<TicketAnswer> OtherAnswers { get; set; }
public TicketAnswer TicketAnswer { get; set; }
}
#Html.HiddenFor(model => model.TicketId, new { Value=Model.Ticket.Id })
So i was able to handle the database with that foreign key, thanks guys

Error in my upload page after i changed my model [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
I added the code to show many checkboxes from my table (HairTags) and in my form CreationUpload.cshtml i got the following error :
An exception of type 'System.NullReferenceException' occurred in
App_Web eba142hb.dll but was not handled in user code Additional
information: Object reference not set to an instance of an object.
Object reference not set to an instance of an object.
<div class="col-md-12">
#for (int i = 0; i < Model.CreationHairTags.Count; i++)
{
#Html.CheckBoxFor(m => Model.CreationHairTags[i].IsChecked)
#Model.CreationHairTags[i].Text
#Html.HiddenFor(m => Model.CreationHairTags[i].Value)
#Html.HiddenFor(m => Model.CreationHairTags[i].Text)<br />
}
</div>
this is my model Creation.cs (in bold the added code)
namespace HairCollection3.Models
{
public class Creation
{
public string UserId { get; set; }
[Key]
public int CreationId { get; set; }
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
[Display(Name = "Sex", ResourceType = typeof(ViewRes.Names))]
public string CreationSex { get; set; }
[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(ViewRes.ValidationStrings))]
[Display(Name = "CreationTitle", ResourceType = typeof(ViewRes.NamesCreation))]
[StringLength(2000)]
[AllowHtml]
public string CreationTitle { get; set; }
public string CreationPhotoBis { get; set; }
public string Creationtag { get; set; }
public virtual ICollection<CreationLike> CreationLikes { get; set; }
}
public class CreationLike
{
public int CreationId { get; set; }
public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }
[Key]
public int CreationLikeId { get; set; }
public virtual Creation ParentCreation { get; set; }
}
public class HairTag
{
[Key]
public int HairTagId { get; set; }
[Required]
public string HairTagTitle { get; set; }
[Required]
public string HairTagType { get; set; }
[Required]
public int HairTagOrder { get; set; }
}
***//CHECKBOXES
public class HairTagModel
{
[Key]
public int Value { get; set; }
public string Text { get; set; }
public bool IsChecked { get; set; }
}
public class HairTagList
{
private ApplicationDbContext creationdb = new ApplicationDbContext();
public HairTagList()
{
var HairTagList = creationdb.HairTags.ToList();
List<HairTagModel> obj = new List<HairTagModel>();
foreach (var tags in HairTagList)
{
obj.Add(new HairTagModel
{
Text = tags.HairTagTitle,
Value = tags.HairTagId,
IsChecked = false
});
}
this.CreationHairTags = obj;
}
public List<HairTagModel> CreationHairTags { get; set; }
//public List<HairTagModel> ListHairTags { get; set; }
}
public class CreationHairTagsModel
{
public Creation Creation { get; set; }
public List<HairTagModel> CreationHairTags { get; set; }
}
}***
My controller CreationController.cs
// GET: /Creation/CreationUpload
[Authorize]
public ActionResult CreationUpload()
{
CreationHairTagsModel creation = new CreationHairTagsModel();
return View(creation);
//return View();
}
// POST: /Creation/CreationUpload
// Afin de déjouer les attaques par sur-validation, activez les propriétés spécifiques que vous voulez lier. Pour
// plus de détails, voir http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public ActionResult CreationUpload([Bind(Include = "CreationId,CreationSex,CreationTitle,CreationPhotoBis,CreationHairTags")] CreationHairTagsModel creation, IEnumerable<HttpPostedFileBase> files)
{
if (ModelState.IsValid)
{
// update each field manually
foreach (var file in files)
{
if (file != null)
{
if (file.ContentLength > 0)
{
....CODE UPLOAD HIDDEN....
//Avoid Script
var CreationTitletocheck = Regex.Replace(creation.Creation.CreationTitle, #"<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>", string.Empty);
CreationTitletocheck = Regex.Replace(CreationTitletocheck, #"(?></?\w+)(?>(?:[^>'""]+|'[^']*'|""[^""]*"")*)>", string.Empty);
creation.Creation.CreationTitle = CreationTitletocheck;
//Tags
StringBuilder sb = new StringBuilder();
foreach (var item in creation.CreationHairTags)
{
if (item.IsChecked)
{
sb.Append(item.Text + ",");
}
}
creation.Creation.Creationtag = sb.ToString();
creation.Creation.UserId = User.Identity.GetUserId();
db.Creations.Add(creation.Creation);
db.SaveChanges();
}
}
}
}
//UserId
return RedirectToAction("CreationList", "Creation", new { UserId = User.Identity.GetUserId() });
}
return View(creation);
}
My page of upload CreationUpload.cshtml
#model HairCollection3.Models.CreationHairTagsModel
#using Microsoft.AspNet.Identity
#{
ViewBag.Title = ViewRes.NamesCreation.CreationUploadTitle;
}
<div class="col-sm-12 col-md-12 chpagetop">
<h1>#ViewRes.Shared.PublishAPhoto</h1>
<hr />
#using (Html.BeginForm("CreationUpload", "Creation", FormMethod.Post, new { id = "CreationUpload", enctype = "multipart/form-data", onsubmit = "$('#creationloading').show(); $('#creationform').hide();" }))
{
#Html.AntiForgeryToken()
<div class="col-md-12" id="creationloading" style="display:none">
<div id="progress">
<p>#ViewRes.Shared.UploadPhotoProgress<strong>0%</strong></p>
<progress value="5" min="0" max="100"><span></span></progress>
</div>
</div>
<div class="col-md-12" id="creationform">
<div class="col-md-12">
#Html.ValidationMessageFor(m => m.Creation.CreationSex)
#Html.RadioButtonFor(m => m.Creation.CreationSex, "F", new { #checked = true }) #ViewRes.Shared.WomanHairstyle #Html.RadioButtonFor(m => m.Creation.CreationSex, "M") #ViewRes.Shared.ManHairstyle
</div>
<div class="col-md-12">
#Html.ValidationMessageFor(m => m.Creation.CreationTitle)
#Html.TextBoxFor(m => m.Creation.CreationTitle, new { #class = "inputplaceholderviolet wid100x100", placeholder = HttpUtility.HtmlDecode(Html.DisplayNameFor(m => m.Creation.CreationTitle).ToHtmlString()), onfocus = "this.placeholder = ''", onblur = "this.placeholder = '" + HttpUtility.HtmlDecode(Html.DisplayNameFor(m => m.Creation.CreationTitle).ToHtmlString()) + "'" })
</div>
<div class="col-md-12">
#for (int i = 0; i < Model.CreationHairTags.Count; i++)
{
#Html.CheckBoxFor(m => Model.CreationHairTags[i].IsChecked)
#Model.CreationHairTags[i].Text
#Html.HiddenFor(m => Model.CreationHairTags[i].Value)
#Html.HiddenFor(m => Model.CreationHairTags[i].Text)<br />
}
</div>
<div class="col-md-12" style="text-align: center">
<p style="display: inline-block">
<input type="file" accept="image/*" onchange="loadFile(event)" name="files" id="file1" translate="yes" data-val="true" data-val-required="A File is required." class="wid100x100" /><label for="file1"></label>
<img id="output" style="max-width:200px;"/>
</p>
</div>
<div class="col-sm-12 col-md-12 chpagetopdiv">
<button type="submit" title="#ViewRes.Shared.Publish"><span class="glyphicon glyphicon-share-alt"></span> #ViewRes.Shared.Publish</button>
</div>
</div>
}
</div>
What is wrong in my code please help and explain ?
Important: In C#, every collection must be initialized before being accessed
The error occurs when you are trying to access from the View to the collection CreationHairTags, which is not initialized. Replace your model to initialize collection in the class constructor:
public class CreationHairTagsModel
{
public Creation Creation { get; set; }
public List<HairTagModel> CreationHairTags { get; set; }
public CreationHairTagsModel()
{
CreationHairTags = new List<HairTagModel>();
}
}

Unable to populate checkbox from database data in mvc 4

This is my Controller code.
public ActionResult Create()
{
ViewBag.grp_id = new SelectList(db.tm_grp_group, "grp_id", "grp_name");
ViewBag.perm_id = new SelectList(db.tm_perm_level, "perm_id", "perm_levelname");
return View();
}
Below is my view code.
#model Permission.ts_grp_perm_mapping
....
#using (Html.BeginForm()) {
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>ts_grp_perm_mapping</legend>
<div class="editor-label">
#Html.LabelFor(model => model.grp_permid)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.grp_permid)
#Html.ValidationMessageFor(model => model.grp_permid)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.grp_id, "tm_grp_group")
</div>
<div class="editor-field">
#Html.DropDownList("grp_id", String.Empty)
#Html.ValidationMessageFor(model => model.grp_id)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.perm_id, "tm_perm_level")
</div>
<div class="editor-field">
#Html.DropDownList("perm_id", String.Empty)
#Html.ValidationMessageFor(model => model.perm_id)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
In controller ViewBag.perm_id contains some values (this is foreign key). In view perm.id displays in the form of dropdownbox but I want it in the form of checkboxlist. How can I achieve this?
This is the viewmodel I created.
public class AssignUserViewModel
{
public tm_perm_level[] perms { get; set; }
public int grp_id { get; set; }
}
Now in controller how can i send values to view? This is my tm_perm_level model
public partial class tm_perm_level
{
public tm_perm_level()
{
this.ts_grp_perm_mapping = new HashSet<ts_grp_perm_mapping>();
}
public int perm_id { get; set; }
public string perm_levelname { get; set; }
public string perm_description { get; set; }
public bool perm_status { get; set; }
public virtual ICollection<ts_grp_perm_mapping> ts_grp_perm_mapping { get; set; }
}
This is ts_grp_perm_mapping model
public partial class ts_grp_perm_mapping
{
public ts_grp_perm_mapping()
{
this.ts_perm_levelmapping = new HashSet<ts_perm_levelmapping>();
}
public int grp_permid { get; set; }
public int grp_id { get; set; }
public int perm_id { get; set; }
public List<tm_perm_level> permissions { get; set; }
public virtual tm_grp_group tm_grp_group { get; set; }
public virtual tm_perm_level tm_perm_level { get; set; }
public virtual ICollection<ts_perm_levelmapping> ts_perm_levelmapping { get; set; }
}
Especially when editing, always start with view models to represent what you want to display (refer What is ViewModel in MVC?)
public class PermissionVM
{
public int ID { get; set; }
public string Name { get; set; }
public bool IsSelected { get; set; }
}
public class GroupPermissionVM
{
public int GroupID { get; set; }
public IEnumerable<SelectListItem> GroupList { get; set; }
public IEnumerable<PermissionVM> Permissions { get; set; }
}
Then create an EditorTemplate for PermissionVM. In the /Views/Shared/EditorTemplates/PermissionVM.cshtml folder
#model PermissionVM
<div>
#Html.HiddenFor(m => m.ID)
#Html.HiddenFor(m => m.Name)
#Html.CheckBoxFor(m => m.IsSelected)
#Html.LabelFor(m => m.IsSelected, Model.Name)
</div>
and the main view will be
#model GroupPermissionVM
....
#using (Html.BeginForm())
{
// dropdownlist
#Html.LabelFor(m => m.GroupID)
#Html.DropDownListFor(m => m.GroupID, Model.GroupList, "Please select")
#Html.ValidationMessageFor(m => m.GroupID)
// checkboxlist
#Html.EditorFor(m => m.Permissions)
<input type="submit" value="Create" />
}
The controller methods would then be
public ActionResult Create()
{
var groups = db.tm_grp_group;
var permissions = db.tm_perm_level;
GroupPermissionVM model = new GroupPermissionVM
{
GroupList = new SelectList(groups, "grp_id", "grp_name"),
Permissions = permissions.Select(p => new PermissionVM
{
ID = p.perm_id,
Name = p.perm_levelname
}
};
return View(model);
}
[HttpPost]
public ActionResult Create(GroupPermissionVM model)
{
if (!ModelState.IsValid)
{
var groups = db.tm_grp_group;
model.GroupList = new SelectList(groups, "grp_id", "grp_name");
return View(model);
}
// map the view model to a new instance of your data model(s)
// note: to get the ID's of the selected permissions -
// var selectedPermissions = model.Permissions.Where(p => p.IsSelected).Select(p => p.ID);
// save and redirect
}
Side note: I strongly recommend you follow normal naming conventions
Edit
Based on OP's comment for an option using radio buttons to select only one item, the revised code would be
public class PermissionVM
{
public int ID { get; set; }
public string Name { get; set; }
}
public class GroupPermissionVM
{
public int GroupID { get; set; }
public int PermissionID { get; set; }
public IEnumerable<SelectListItem> GroupList { get; set; }
public IEnumerable<PermissionVM> Permissions { get; set; }
}
and the view would be (no separate EditorTemplate required)
#model GroupPermissionVM
....
#using (Html.BeginForm())
{
// dropdownlist as above
// radio buttons
foreach (var permission in Model.Permissions)
{
<label>
#Html.RadioButtonForm(m => m.PermissionID, permission.ID)
<span>#permission.Name</span>
</label>
}
<input type="submit" value="Create" />
}
and in the POST method, the value of model.PermissionID will contain the ID of the selected Permission.

asp.net mvc5 validating list of objects

I have a view for entering delivery quantities on every items in the list, and sends a list of objects back to controller. I would like to validate all textboxes on the page, and I have added annotations in the model.
The problem is, I can only validate the first row (also in the output html only the first row has validation markups). Since there are generated validations on the first row, so I don't think it's about the model. Is there a way to have generated validations in all rows? If not, what are the workarounds?
#{int i = 0;}
#foreach (var item in Model)
{
<tr>
<td>
#Html.HiddenFor(modelItem => item.eo, new { Name = "[" + i + "].eo" })
#Html.DisplayFor(modelItem => item.barcode)
#Html.Hidden("[" + i + "].barcode", Model[i].barcode)
</td>
<td>
#Html.DisplayFor(modelItem => item.itemno)
</td>
<td>
#Html.DisplayFor(modelItem => item.cdesc)
</td>
<td>
#Html.DisplayFor(modelItem => item.acost)
</td>
<td>
#Html.DisplayFor(modelItem => item.qty)
</td>
<td>
#Html.EditorFor(modelItem => item.dqty, new { htmlAttributes = new { Name = "[" + i + "].dqty", id = "[" + i + "].dqty", #class = "form-control" } })
#Html.ValidationMessage("[" + i + "].dqty", "", new { #class = "text-danger" })
</td>
</tr>
i++;
}
This is the generated html for the textbox in the first row.
<input Name="[0].dqty" class="form-control text-box single-line" data-val="true" data-val-number="The field 出貨數量 must be a number." data-val-required="必須填上出貨數量" id="[0].dqty" name="item.dqty" type="text" value="10" />
<span class="field-validation-valid text-danger" data-valmsg-for="[0].dqty" data-valmsg-replace="true"></span>
And the second row onwards...
<input Name="[1].dqty" class="form-control text-box single-line" id="[1].dqty" name="item.dqty" type="text" value="7" />
<span class="field-validation-valid text-danger" data-valmsg-for="[1].dqty" data-valmsg-replace="true"></span>
The Model
[MetadataType(typeof(EorderDetailsMetaData))]
public partial class EorderDetails
{
public string eo { get; set; }
public string barcode { get; set; }
public string itemno { get; set; }
public string cdesc { get; set; }
public Nullable<decimal> qty { get; set; }
public Nullable<decimal> dqty { get; set; }
public Nullable<decimal> acost { get; set; }
public string sdate { get; set; }
public string edate { get; set; }
public string shop { get; set; }
public string sname { get; set; }
public string saddr { get; set; }
public string shoptel { get; set; }
public string shopfax { get; set; }
}
public class EorderDetailsMetaData
{
[Display(Name = "訂單編號")]
public string eo { get; set; }
[Display(Name = "電腦條碼")]
public string barcode { get; set; }
[Display(Name = "貨品編號")]
public string itemno { get; set; }
[Display(Name = "貨品名稱")]
public string cdesc { get; set; }
[Display(Name = "訂購數量")]
[DisplayFormat(DataFormatString = "{0:n0}", ApplyFormatInEditMode = true)]
public Nullable<decimal> qty { get; set; }
[Display(Name = "出貨數量")]
[DisplayFormat(DataFormatString = "{0:n0}", ApplyFormatInEditMode = true)]
[Required(ErrorMessage = "必須填上出貨數量")]
public Nullable<decimal> dqty { get; set; }
[Display(Name = "成本價")]
[DisplayFormat(DataFormatString = "{0:0.##}", ApplyFormatInEditMode = true)]
public Nullable<decimal> acost { get; set; }
public string sdate { get; set; }
public string edate { get; set; }
public string shop { get; set; }
public string sname { get; set; }
public string saddr { get; set; }
public string shoptel { get; set; }
public string shopfax { get; set; }
}
You should be generating the collection in a for loop and let the helpers generate the correct html for you. If you inspect the html you have posted in the second snippet you will see the issue (two name attributes!)
#model IList<EorderDetails>
#using(Html.BeginForm())
{
for(int i = 0; i < Model.Count; i++)
{
#Html.HiddenFor(m => m[i].eo)
#Html.DisplayFor(m => m[i].barcode)
....
#Html.EditorFor(m => m[i].dqty, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(m => m[i].dqty, new { #class = "text-danger" })
}
<input type="submit" />
}
Alternatively you can create a custom EditorTemplate for your model
/Views/Shared/EditorTemplates/EorderDetails.cshtml
#model EorderDetails
#Html.HiddenFor(m => m.eo)
#Html.DisplayFor(m => m.barcode)
....
and in the main view
#model IList<EorderDetails>
#using(Html.BeginForm())
{
#Html.EditorFor(m => m)
<input type="submit" />
}
To omit this strange behavior, there should:
Define the property as Array, instead of ICollection or IList.
Should use for in cshtml, instead of forEach.
Have no idea why this will cause the difference. But I think it should not. And I think this is a bug should be fixed.

Resources