foreach in foreach error build - c#

I need to do a loop in another loop and I get a strange error as if it lacked a closing } and I get a compile error on the page. As against the project compiles . the error message is
CS1513 : } expected.
The source indicates the line of code in 1238 while I was not more than 150 lines of code in the page, really strange . help please
#using (Html.BeginForm("VCreateCommande", "CCommande", new { id = "formretouche" }, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="control-label col-md-2">Support papier</div>
<div class="col-md-10">
#Html.CheckBoxFor(model => model.Tretouche.Supportpapier, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Tretouche.Supportpapier, "", new { #class = "text-danger" })
</div>
</div>
var i = 1;
foreach (var item in Model.Tformats)
{
var idformat = "idformat" + i;
var idquantite = "qteformat" + i;
var idtxt="qte" + #item.Idformat;
int qteretoucheformat=0;
foreach (var itemretoucheformat in Model.Tretouchesformats)
{
if(itemretoucheformat.IdFormat ==item.Idformat)
{
qteretoucheformat = itemretoucheformat.Quantité;
}
}
<div>
<div class="form-group">
<div class="control-label col-md-2 fltleft">Quantité #item.Format</div>
<div class="col-md-10 fltleft">
#Html.TextBoxFor(model => model.Tretoucheformat.Quantité, new { id = idtxt, Name=idtxt })
#Html.ValidationMessageFor(model => model.Tretoucheformat.Quantité, "", new { #class = "text-danger" })
</div>
</div>
</div>
i = i + 1;
}
<div class="form-group">
<div class="control-label col-md-2">Photo...</div>
<div class="col-md-10">
#Html.TextBoxFor(model => model.Tretouche.fichierphoto, new { type = "file" })
</div>
</div>
<input id="idtyperetouche" name="idtyperetouche" type="text" value="#idtyperetouche" class="hdn" />
<input name="idcommande" type="text" value="#idtyperetouche" class="hdn" />
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Ajouter" class="btn btn-default" />
</div>
</div>
}
<table class="table">
<tr>
<th>Papier</th>
<th>Quantite</th>
<th>Type de retouche</th>
<th>Photo</th>
</tr>
#foreach (var item in Model.Tretouches)
{
var prix = 0;
<tr>
<td>
#Html.CheckBox("Papier", item.Supportpapier)
</td>
<td>
#Html.DisplayFor(modelItem => item.Quantite)
</td>
#foreach (var typeretouche in Model.Ttyperetouches)
{
if (item.Idtyperetouche == typeretouche.Idtyperetouche)
{
<td>#typeretouche.Libelle</td>
prix = (typeretouche.Prix * item.Quantite);
}
}
<td>
<img src="#item.SRCphoto" class="">
</td>
<td>
#prix €
</td>
<td>
#Html.ActionLink("Modifier", "Edit", "TRetouches", new { id = item.Idretouche }, null) |
#Html.ActionLink("Supprimer", "Delete", "TRetouches", new { id = item.Idretouche }, null)
</td>
</tr>
}

For Razor views (at least MVC 4 and earlier), unlike for a .cs file, the { needs to be on its own line
foreach (var itemretoucheformat in Model.Tretouchesformats)
{
}
Henk's comment suggests this may have been improved in MVC 5.

Related

VIEW MODAL UPDATE IN ASP.NET MVC and C#

I have a view, which shows a list of items consumed in a div and other details of a complaint in another div. Now, these items consumed div can have multiple records against a complaint. How to add new records and then refresh the div while still showing the original view. How to work around the problem. I did try to use modal popup but after submission and record update in the table, it's still showing the modal, whereas it needs to refresh the view itself.
This join view has edit option to set status, which leads to the problem view mentioned above.
In the status set view , i have multiple data such as id etc. in one div, Another div which contains the list of materials consumed so far. This div where consumption details are loaded as a list needs to be updated , as in new records to be updated and the updated view should be generated.
I need to dynamically add new material in the other div based on dropdown selection(hide/Show). and after submission, the tables needs to be updated.
public ActionResult StatusEdit(int id, int statuscode, string statusaction, int regid, short appid, short dep, short com )
{
DisplayEC dn = new DisplayEC();
DbAccess da = new DbAccess();
dn.ComplnId = com;
dn.JobC = id;
///dn.MatId = mat;
///dn.StDate = sdate;
dn.DeptCode = dep;
dn.Appid = appid;
dn.statcode = statuscode;
dn.statacn = statusaction;
dn.Regid = regid;
dn.JbStsDate = DateTime.Now.ToString();
dn.DeptCode = Convert.ToByte(Session["departmentno"]);
dn.ListJobStatus = new List<System.Web.Mvc.SelectListItem>();
dn.ListJobStatus = da.GetAllJobStatus(dn.DeptCode, appid);
dn.ListJobHistory = new List<JobStatus>();
dn.ListJobMaterials = new List<DispJobMaterial>();
dn.JobCode = dn.JobC.ToString();
if ((dn.DeptCode > 0) && (!string.IsNullOrEmpty(dn.JobCode)))
{
dn.ListJobHistory = da.GetJobStatusHistory(dn.DeptCode, dn.Appid, Convert.ToInt32(dn.JobC));
dn.ListJobMaterials = da.GetMaterialsConsumed(dn.DeptCode, Convert.ToByte(dn.Appid), Convert.ToInt32(dn.JobC));
}
dn.ListMaterials = new List<System.Web.Mvc.SelectListItem>();
dn.ListMaterials = da.GetMaterialsByUserType(dn.DeptCode, dn.Appid, "DEPTUSER");
return View(dn);
}
View:
#using System.Web.Helpers
#model EC.ViewModels.DisplayEC
#{
Layout = "~/Views/Shared/_Layout1.cshtml";
}
<br />
<br />
<a style="cursor: pointer; font-size: 30px; color:darkblue" title="Home" class="fa fa-home pull-left" href="#Url.Action("JoinView", "Admin")"></a>
<a style="cursor: pointer; font-size: 30px; color:darkblue" title="Log Out" class="fa fa-sign-out pull-right" href="#Url.Action("Login", "Account")"></a>
<br /><br />
<h4 class="display-4" style="display: inline;">JOBCODE :: <span style="color:red">#Model.JobCode</span></h4>
<div class="mt-5">
#*#using (Html.BeginForm("StatusEdit", "Admin", FormMethod.Post, new { id = "StatusEdit", #class = "", role = "form" }))*#
#using (Html.BeginForm("StatusEdit", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
#Html.HiddenFor(x => x.JobC)
#Html.HiddenFor(x => x.JobCode)
#Html.HiddenFor(x => x.DeptCode)
#Html.HiddenFor(x => x.Appid)
#Html.HiddenFor(x => x.statcode)
#Html.HiddenFor(x => x.statacn)
#Html.HiddenFor(x => x.Regid)
#Html.HiddenFor(x => x.JbStsDate)
#Html.HiddenFor(x => x.Regid)
#*#Html.HiddenFor(x => x.JobStatusCode)*#
#Html.HiddenFor(x => x.ComplnId)
#Html.HiddenFor(x => x.MatId)
#Html.HiddenFor(x => x.StDate)
<div>
#if (TempData["notice"] != null)
{
<h4 class="alert alert-danger" id="successMessage">#TempData["notice"]</h4>
}
</div>
<table class="table table-borderless" style="width:100%">
<tbody>
<tr>
<td style="width:50%">
<div class="card">
<div class="card-header bg-secondary"><span style="font-weight:bold;color:white">JOB STATUS</span></div>
<div class="card-body">
<table class="table table-borderless" style="width:100%;margin-bottom:0;padding-bottom:0">
<tbody>
<tr>
<td style="width:30%">
<div class="form-group">
#Html.LabelFor(x => x.JobStatusCode, new { #class = "control-label label_text" })
<div>
#if (string.IsNullOrEmpty(Model.JobCode))
{
#Html.DropDownListFor(x => x.JobStatusCode, new SelectList(Model.ListJobStatus.ToList().Where(x => x.Value != "1").Where(x => x.Value != "2").Where(x => x.Value != "3").Where(x => x.Value != "6").Where(x => x.Value != "7").Where(x => x.Value != "5").ToList(), "Value", "Text", Model.JobStatusCode), new { #class = "form-control", #disabled = "true", id = "ddlCategory" })
}
else
{
#Html.DropDownListFor(x => x.JobStatusCode, new SelectList(Model.ListJobStatus.ToList().Where(x => x.Value != "1").Where(x => x.Value != "2").Where(x => x.Value != "3").Where(x => x.Value != "6").Where(x => x.Value != "7").Where(x => x.Value != "5").ToList(), "Value", "Text", Model.JobStatusCode), new { #class = "form-control", id = "ddlCategory" })
}
#Html.ValidationMessageFor(x => x.JobStatusCode)
</div>
</div>
</td>
<td style="width:20%">
<div class="form-group">
#Html.LabelFor(x => x.JbStsDate, new { #class = "control-label label_text" })
<div>
#Html.TextBoxFor(x => x.JbStsDate, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.JbStsDate)
</div>
</div>
</td>
<td style="width:30%">
<div class="form-group">
#Html.LabelFor(x => x.JobStatusRemark, new { #class = "control-label label_text" })
<div>
#Html.TextBoxFor(x => x.JobStatusRemark, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.JobStatusRemark)
</div>
</div>
</td>
<td style="width:20%">
<div class="form-group" style="padding-top: 30px;">
<button id="btnAddSts" type="button" disabled="disabled" class="btn btn-info pull-left"><i class="fa fa-plus-square"></i> Add Status</button>
</div>
</td>
</tr>
</tbody>
</table>
<table id="JbStsHtry" class="table table-responsive-md table-hover" style="width:100%">
<tbody>
#for (int i = 0; i < Model.ListJobHistory.Count; i++)
{
<tr class="h-divider_sts">
<td style="width:40%">
<span>#Html.DisplayFor(x => x.ListJobHistory[i].StatusText)</span>
</td>
<td style="width:20%">
<span>#Model.ListJobHistory[i].StatusDate.ToShortDateString()</span>
</td>
<td style="width:30%">
<span>#Html.DisplayFor(x => x.ListJobHistory[i].StatusRemarks)</span>
</td>
<td style="width:10%">
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</td>
<td style="width:50%" id="Other">
<div class="card">
<div class="card-header bg-secondary">
<span style="font-weight:bold;color:white">Material Consumed</span>
</div>
<div class="card-body">
<table class="table table-borderless table-responsive-md" style="width:100%;margin-bottom:0;padding-bottom:0">
<tbody>
<tr style="width:20%">
<th>#Html.LabelFor(x => x.JobMaterialId, new { #class = "control-label label_text" })</th>
<th> #Html.LabelFor(x => x.MatrlQty, new { #class = "control-label label_text" })</th>
</tr>
<tr>
<td style="width:40%">
<div class="form-group">
#*#Html.LabelFor(x => x.JobMaterialId, new { #class = "control-label label_text" })*#
<div>
#if (string.IsNullOrEmpty(Model.JobCode))
{
#Html.DropDownListFor(x => x.JobMaterialId, new SelectList(Model.ListMaterials, "Value", "Text", Model.JobMaterialId), new { #class = "form-control", #disabled = "true" })
}
else
{
#Html.DropDownListFor(x => x.JobMaterialId, new SelectList(Model.ListMaterials, "Value", "Text", Model.JobMaterialId), new { #class = "form-control" })
}
#Html.ValidationMessageFor(x => x.JobMaterialId)
</div>
</div>
</td>
<td style="width:30%">
<div class="form-group">
#*#Html.LabelFor(x => x.MatrlQty, new { #class = "control-label label_text" })*#
<div>
#Html.TextBoxFor(x => x.MatrlQty, new { #class = "form-control" })
#Html.ValidationMessageFor(x => x.MatrlQty)
</div>
</div>
</td>
<td style="width:30%">
<div class="form-group" style="padding-top: 30px;">
<button id="btnAdd" class="btn btn-info pull-left"><i class="fa fa-plus-square"></i> Add Material</button>
</div>
</td>
</tr>
</tbody>
</table>
#*<table id="JbMatrl" class="table table-responsive-md table-hover" style="width:100%">*#
<table id="JbMatrl" class="table table-responsive-md table-hover" style="width:100%">
<tbody>
#for (int i = 0; i < Model.ListJobMaterials.Count; i++)
{
<tr class="h-divider_sts">
<td style="width:50%">
#Html.DisplayFor(x => x.ListJobMaterials[i].MaterialText)
</td>
<td style="width:50%">
#Html.DisplayFor(x => x.ListJobMaterials[i].MaterialQty)
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
</td>
<td style="width:50%" id="Other2">
</td>
</tr>
</tbody>
</table>
<div class="form-group" style="padding-top: 30px;">
<button type="submit" class="btn btn-info pull-left"><i class="fa fa-plus-square"></i> Submit</button>
</div>
}
</div>
<br />
\\\\\\\\
<script type="text/javascript">
$(document).ready(function () {
$("#ddlCategory").change(function () {
var e = document.getElementById("ddlCategory");
var value = e.options[e.selectedIndex].text;
if (value == "Assignment Cancelled") {
$('#Other').hide();
$('#Other2').show();
} else {
$('#Other').show();
$('#Other2').hide();
}
});
});
</script>

MVC Textbox binding multiple properties

I am trying to figure out the best way to present/save the data in a view I am creating.
I am not wedded to the underlying table structure, and have played around with it trying to get the best outcome but no luck.
Effectively I have multiple textbox's that need to be saved back to the database, but due to the view layout (and it really needs to stay in this layout), I need to populate additional columns with hard coded info.
In my view I have just repeated the textbox ( I tried to index it, but got an error saying it wasn't possible on decimal data types?)
Below is my model
namespace Testing.Models
{
public partial class OnFarm
{
public int Id { get; set; }
public Guid? Tracker { get; set; }
public int Year { get; set; }
public decimal? Period1 { get; set; }
public decimal? Period2 { get; set; }
public decimal? Period3 { get; set; }
public decimal? Period4 { get; set; }
public decimal? Period5 { get; set; }
public decimal? Period6 { get; set; }
public decimal? Period7 { get; set; }
public decimal? Period8 { get; set; }
public decimal? Period9 { get; set; }
public decimal? Period10 { get; set; }
public decimal? Period11 { get; set; }
public decimal? Period12 { get; set; }
public int Version { get; set; }
public int Account { get; set; }
public int MvtType { get; set; }
public virtual Account AccountNavigation { get; set; }
public virtual MovementType MvtTypeNavigation { get; set; }
public virtual ProductionModule TrackerNavigation { get; set; }
public virtual Version VersionNavigation { get; set; }
public virtual Years YearNavigation { get; set; }
}
}
This is my controller as it stands currently
public IActionResult Create(Guid? id)
{
var query = _context.LegalEntities.FromSqlRaw("Select DISTINCT B.* From Client.Groups a Left join Client.[Legal Entities] b on b.Parent = a.ID left join client.Enterprises c on c.Parent = b.ID left join client.[Production Module] d on d.Parent = c.ID left join OnFarm.[On Farm] e on e.Tracker = d.ID Where e.id IS NOT NULL AND a.id = {0}", id).ToList();
List<SelectListItem> LEList = new List<SelectListItem>();
foreach (var m in query)
{
LEList.Add(new SelectListItem { Text = m.Name, Value = m.Id.ToString() });
}
ViewBag.LE = LEList;
var acclist = _context.Accounts.Where(x => x.AccountCatId == 92100).ToList().OrderBy(x => x.Description);
List<SelectListItem> listac = new List<SelectListItem>();
listac.Add(new SelectListItem { Text = "--Select Livestock Type--", Value = "0" });
if (acclist != null)
{
var i = 1;
foreach (var x in acclist)
{
listac.Add(new SelectListItem { Text = x.Description, Value = x.Number.ToString() });
i += 1;
}
}
ViewBag.Account = listac;
ViewData["MvtType"] = new SelectList(_context.MovementTypes, "Id", "Type");
ViewData["Tracker"] = new SelectList(_context.ProductionModules, "Id", "Name");
ViewData["Version"] = new SelectList(_context.Versions, "VersionId", "VersionName");
ViewData["Year"] = new SelectList(_context.Year, "Id", "Year");
return View();
}
Here is my view
<div class="row">
#foreach (var item in ViewBag.LE)
{
<div class="panel panel-default rounded shadow col-11">
<div class="panel-heading border-bottom">
<div class="no-gutters"><h4><b>#item.Text</b></h4></div>
</div>
<div class="panel-body">
<div class="row">
#foreach (var i in ViewBag.Tracker)
{
<div class="row d-flex align-items-center">
<div class="panel panel-default rounded shadow col">
<div class="panel-heading border-bottom">
<div class="no-gutters text-muted col-5"><h3><b> #i.Text</b></h3></div>
<div class="col-2">
<select asp-for="Account" class="form-control" asp-items="ViewBag.Account"></select>
</div>
</div>
<div class="panel-body">
<div class="row d-flex align-items-center">
<div class="col-1"><b>Month</b></div>
<div class="col-1 d-flex justify-content-center"><b>Opening Balance</b></div>
<div class="col-1 d-flex justify-content-center"><b>Births</b></div>
<div class="col-1 d-flex justify-content-center"><b>Deaths</b></div>
<div class="col-1 d-flex justify-content-center"><b>Purchases</b></div>
<div class="col-1 d-flex justify-content-center"><b>Sold</b></div>
<div class="col-1 d-flex justify-content-center"><b>Age In</b></div>
<div class="col-1 d-flex justify-content-center"><b>Age Out</b></div>
<div class="col-1 d-flex justify-content-center"><b>Adjustments</b></div>
<div class="col-1 d-flex justify-content-center"><b>Closing Balance</b></div>
</div>
<div class="row d-flex align-items-center">
<div class="col-1">
Apr
</div>
<div class="col-1">
#Html.TextBoxFor(m => m.Period1, new { #class = "form-control", disabled = "disabled" })
<span asp-validation-for="Period1" class="text-danger"></span>
</div>
<div class="col-1">
#Html.TextBoxFor(m => m.Period1, new { #class = "form-control" })
<span asp-validation-for="Period1" class="text-danger"></span>
</div>
<div class="col-1">
#Html.TextBoxFor(m => m.Period1, new { #class = "form-control" })
<span asp-validation-for="Period1" class="text-danger"></span>
</div>
<div class="col-1">
#Html.TextBoxFor(m => m.Period1, new { #class = "form-control" })
<span asp-validation-for="Period1" class="text-danger"></span>
</div>
<div class="col-1">
#Html.TextBoxFor(m => m.Period1, new { #class = "form-control" })
<span asp-validation-for="Period1" class="text-danger"></span>
</div>
<div class="col-1">
#Html.TextBoxFor(m => m.Period1, new { #class = "form-control" })
<span asp-validation-for="Period1" class="text-danger"></span>
</div>
<div class="col-1">
#Html.TextBoxFor(m => m.Period1, new { #class = "form-control" })
<span asp-validation-for="Period1" class="text-danger"></span>
</div>
<div class="col-1">
#Html.TextBoxFor(m => m.Period1, new { #class = "form-control" })
<span asp-validation-for="Period1" class="text-danger"></span>
</div>
<div class="col-1">
#Html.TextBoxFor(m => m.Period1, new { #class = "form-control", disabled = "disabled" })
<span asp-validation-for="Period1" class="text-danger"></span>
</div>
</div>
</div>
</div>
</div>
}
</div>
</div>
</div>
}
</div>
Now the panel body is repeated 12 times (for each month of the year).
When saving data back, I will have some hidden fields for some of the core info. BUT what i need to be able to do is when saving back the first text box it also needs to save the MvtType (hard coded as column headings) as a column value.
I will wrap the panels into a form so it will submit when a button is clicked.
Finally, the underlying table. I used to have a column called period, one called value, as thought that might have been a better way of doing it? Rather than each period separated out.
Oh and sorry, I will need to load data to these textboxes when loading the page
Any help is much appreciated
EDIT
Ok, so i have made some progress here. I have tided up my view (See below) and can now get my view to pass back the first column of movement types, but nothing in the other columns. I effectively want to be able to post back a value into the period column while adding a value to the Mvt Type Column.
<div class="row">
#foreach (var item in ViewBag.LE)
{
<div class="panel panel-default rounded shadow col-11">
<div class="panel-heading border-bottom">
<div class="no-gutters"><h4><b>#item.Text</b></h4></div>
</div>
<div class="panel-body">
<div class="row">
#foreach (var i in ViewBag.Tracker)
{
<form asp-action="Create" class="form-group">
<div class="form-group">
<label asp-for="Tracker" class="control-label"></label>
<select asp-for="Tracker" class="form-control" asp-items="ViewBag.Tracker"></select>
</div>
<div class="form-group">
<label asp-for="Year" class="control-label"></label>
<select asp-for="Year" class="form-control" asp-items="ViewBag.Year"></select>
</div>
<div class="form-group">
<label asp-for="Version" class="control-label"></label>
<select asp-for="Version" class="form-control" asp-items="ViewBag.Version"></select>
</div>
<div class="row d-flex align-items-center">
<div class="panel panel-default rounded shadow col">
<div class="panel-heading border-bottom">
<div class="no-gutters text-muted col-5"><h3><b> #i.Text</b></h3></div>
<div class="col-2">
<select asp-for="Account" class="form-control" asp-items="ViewBag.Account"></select>
</div>
</div>
<div class="panel-body">
<div class="row d-flex align-items-center">
<div class="col-1"><b>Month</b></div>
<div class="col-1 d-flex justify-content-center"><b>Opening Balance</b></div>
#foreach (var mvt in ViewBag.MVtType)
{
<div class="col-1 d-flex justify-content-center">
<b>#mvt.Text</b>
</div>
}
<div class="col-1 d-flex justify-content-center"><b>Closing Balance</b></div>
</div>
<div class="row d-flex align-items-center">
<div class="col-1">
Apr
</div>
<div class="col-1">
#Html.TextBoxFor(m => m.Period1, new { #class = "form-control", disabled = "disabled" })
<span asp-validation-for="Period1" class="text-danger"></span>
</div>
#for (int z = 0; z < ViewBag.MvtType.Count; z++)
{
<div class="col-1">
<select asp-for= "MvtType" class="form-control" asp-items="ViewBag.MvtType"></select>
#Html.TextBoxFor(m => m.Period1, new { #class = "form-control" })
<span asp-validation-for="Period1" class="text-danger"></span>
</div>
}
<div class="col-1">
#Html.TextBoxFor(m => m.Period1, new { #class = "form-control", disabled = "disabled" })
<span asp-validation-for="Period1" class="text-danger"></span>
</div>
</div>
</div>
</div>
</div>
<div class="row d-flex align-items-center">
<div class="col-8"></div>
<div class="col-2">
<input type="submit" value="Save" class="btn btn-primary float-right" />
</div>
</div>
</form>
}
</div>
</div>
</div>
}
</div>
Righto, I have managed to find the answer.
Following this guide here Editing Multiple records using model binding in MVC
I have gotten my answer.
My view now looks like this, allowing indexing of the textboxes so I can edit multiple records, and not just one! I will update it to make it look prettier, and to hide certain fields
<div class="panel-body">
#using (Html.BeginForm("Index","OnFarms", FormMethod.Post))
{
<table class="table">
#for (int z = 0; z < Model.Count; z++)
{
<tr>
<td>
#Html.TextBox("OnFarms[" + #z + "].Id", Model[z].Id, new { #class = "form-Control" })
</td>
<td>
#Html.TextBox("OnFarms[" + #z + "].Tracker", Model[z].Tracker, new { #class = "form-Control" })
</td>
<td>
#Html.TextBox("OnFarms[" + #z + "].Year", Model[z].Year, new { #class = "form-Control" })
</td>
<td>
#Html.TextBox("OnFarms[" + #z + "].Period1", Model[z].Period1, new { #class = "form-Control" })
</td>
<td>
#Html.TextBox("OnFarms[" + #z + "].Period2", Model[z].Period2, new { #class = "form-Control" })
</td>
<td>
#Html.TextBox("OnFarms[" + #z + "].Period3", Model[z].Period3, new { #class = "form-Control" })
</td>
<td>
#Html.TextBox("OnFarms[" + #z + "].Period4", Model[z].Period4, new { #class = "form-Control" })
</td>
<td>
#Html.TextBox("OnFarms[" + #z + "].Period5", Model[z].Period5, new { #class = "form-Control" })
</td>
<td>
#Html.TextBox("OnFarms[" + #z + "].Period6", Model[z].Period6, new { #class = "form-Control" })
</td>
<td>
#Html.TextBox("OnFarms[" + #z + "].Period7", Model[z].Period7, new { #class = "form-Control" })
</td>
<td>
#Html.TextBox("OnFarms[" + #z + "].Period9", Model[z].Period9, new { #class = "form-Control" })
</td>
<td>
#Html.TextBox("OnFarms[" + #z + "].Period10", Model[z].Period10, new { #class = "form-Control" })
</td>
<td>
#Html.TextBox("OnFarms[" + #z + "].Period11", Model[z].Period11, new { #class = "form-Control" })
</td>
<td>
#Html.TextBox("OnFarms[" + #z + "].Period12", Model[z].Period12, new { #class = "form-Control" })
</td>
<td>
#Html.TextBox("OnFarms[" + #z + "].Version", Model[z].Version, new { #class = "form-Control" })
</td>
<td>
#Html.TextBox("OnFarms[" + #z + "].Account", Model[z].Account, new { #class = "form-Control" })
</td>
<td>
#Html.TextBox("OnFarms[" + #z + "].MvtType", Model[z].MvtType, new { #class = "form-Control" })
</td>
<td>
</td>
</tr>
}
</table>
<input type="submit" value="Submit" />
}
</div>
But the key was to change the #model to be #model List<Testing.Models.OnFarm> not just Testing.Models.OnFarm
and my controller is simply
public ActionResult Index(List<OnFarm> OnFarms)
{
foreach (OnFarm frm in OnFarms)
{
OnFarm Existed_Mvt = _context.OnFarms.Find(frm.Id);
Existed_Mvt.Tracker = frm.Tracker;
Existed_Mvt.Year = frm.Year;
Existed_Mvt.Period1 = frm.Period1;
Existed_Mvt.Period2 = frm.Period2;
Existed_Mvt.Period3 = frm.Period3;
Existed_Mvt.Period4 = frm.Period4;
Existed_Mvt.Period5 = frm.Period5;
Existed_Mvt.Period6 = frm.Period6;
Existed_Mvt.Period7 = frm.Period7;
Existed_Mvt.Period8 = frm.Period8;
Existed_Mvt.Period9 = frm.Period9;
Existed_Mvt.Period10 = frm.Period10;
Existed_Mvt.Period11 = frm.Period11;
Existed_Mvt.Period12 = frm.Period12;
Existed_Mvt.Version = frm.Version;
Existed_Mvt.Account = frm.Account;
Existed_Mvt.MvtType = frm.MvtType;
}
_context.SaveChanges();

Html.BeginForm FormMethod.Post is not working

I want to post my data to the action which is HttpPost. I always do it but this time I don't know what happens here. Submit button sends view data to Get action (I mean Detail action which is HttpGet) the button type is submit as you see and in the Html.BeginForm as you see I have used FormMethod.Post but just sends dar. I searched here but found nothing.
View:
#using MF_Urmia.Models.ViewModels
#using Kendo.Mvc.UI
#model CourseVm
#{
Layout = "~/Areas/Admin/Views/Shared/_LayoutPage.cshtml";
}
#using(Html.BeginForm("Detail", "Course", FormMethod.Post))
{
#Html.HiddenFor(m => m.CourseId)
#Html.ValidationSummary(true)
<div class="form-column">
<h1 class="form-title-box">
<span class="form-title">
#ViewBag.title
</span>
</h1>
<div class="frm-group">
<div class="form-label form-required">
#Html.LabelFor(m => m.CourseName)
</div>
<div class="form-field">
#Html.TextBoxFor(m => m.CourseName, new { #class = "k-textbox" })
</div>
</div>
<div class="frm-group">
<div class="form-label form-required">
#Html.LabelFor(m => m.TypeName)
</div>
<div class="form-field">
#(Html.Kendo().DropDownListFor(m => m.CourseTypeId)
.BindTo((IEnumerable<SelectListItem>)ViewBag.CourseTypeList)
.OptionLabel("(Select One)")
.DataValueField("Value")
.DataTextField("Text")
.HtmlAttributes(new { id = "CourseType" }))
</div>
</div>
<div class="frm-group">
<div class="form-label form-required">
#Html.LabelFor(m => m.Price)
</div>
<div class="form-field">
#Html.TextBoxFor(m => m.Price, new { #class = "k-textbox", #type = "number"})
</div>
</div>
<br />
<div class="frm-group">
<div class="form-label form-required">
#Html.LabelFor(m => m.Copacity)
</div>
<div class="form-field">
#Html.TextBoxFor(m => m.Copacity, new { #class = "k-textbox", #type = "number" })
</div>
</div>
<div class="frm-group">
<div class="form-label form-required">
#Html.LabelFor(m => m.TeacherName)
</div>
<div class="form-field">
#Html.TextBoxFor(m => m.TeacherName, new { #class = "k-textbox" })
</div>
</div>
<div class="frm-group">
<div class="form-label form-required">
#Html.LabelFor(m => m.DurationTime)
</div>
<div class="form-field">
#Html.TextBoxFor(m => m.DurationTime, new { #class = "k-textbox", #type = "number" })
</div>
</div>
<br />
<div class="frm-group">
<div class="form-label form-required">
#Html.LabelFor(m => m.ClassStart)
</div>
<div class="form-field">
#Html.TextBoxFor(model => model.ClassStart, new { #class = "form-control kendo-date-picker", value = "", placeholder = "مثال :1396/05/20" })
</div>
</div>
<div class="frm-group">
<div class="form-label">
#Html.LabelFor(m => m.RegisterLimit)
</div>
<div class="form-field">
#Html.TextBoxFor(model => model.RegisterLimit, new { #class = "form-control kendo-date-picker", value = "", placeholder = "مثال :1396/05/20" })
</div>
</div>
<hr />
<div class="frm-group">
<div class="form-label form-required">
#Html.LabelFor(m => m.CourseImage)
</div>
<div class="form-field-2xl">
#Html.Kendo().Upload().Name("ImageFile").Messages(m => m.Select("select")).Multiple(false)
</div>
</div>
<hr />
<div class="frm-group">
<div class="form-label">
#Html.LabelFor(m => m.Description)
</div>
<div class="form-field full-width">
#Html.TextAreaFor(m => m.Description, new { #class = "k-textbox ck-editor-box" })
</div>
</div>
<hr />
<input value="submit" type="submit" class="btn btn-success form-btn" />
</div>
}
Controller:
public ActionResult Detail(int? id)
{
var courseId = id;
using (var db = new MFUEntities())
{
var courseTypeList = db.CourseType.ToList();
ViewBag.CourseTypeList = new SelectList(courseTypeList,
nameof(CourseType.CourseTypeId), nameof(CourseType.DisplayName));
if (courseId.HasValue)
{
//ويرايش
ViewBag.title = "Edit";
return View();
}
else
{
//ثبت
ViewBag.title = "Create";
return View();
}
}
}
[HttpPost]
public ActionResult Detail(CourseVm vm)
{
var courseId = vm.CourseId;
using (var db = new MFUEntities())
{
if (courseId > 0)
{
//Edit
var course = db.Course.FirstOrDefault(c => c.CourseId == vm.CourseId);
if (course == null)
{
return HttpNotFound();
}
//ويرايش عکس دوره
var oldImage = course.CourseImage;
//عکس قبلي را پاک کند
System.IO.File.Delete(Server.MapPath("/Images/CourseImage/Images/" + oldImage));
System.IO.File.Delete(Server.MapPath("/Images/CourseImage/Thumb/" + oldImage));
vm.CourseImage = Guid.NewGuid().ToString().Replace("-", "") +
Path.GetExtension(vm.ImageFile.FileName);
vm.ImageFile.SaveAs(Server.MapPath("/Images/CourseImage/Images/" + vm.CourseImage));
ImageResizer img = new ImageResizer();
img.Resize(Server.MapPath("/Images/CourseImage/Images/" + vm.CourseImage),
Server.MapPath("/Images/CourseImage/Thumb/" + vm.CourseImage));
Mapper.Map(vm, course);
}
else
{
//Create
//ثبت عکس دوره
vm.CourseImage = Guid.NewGuid().ToString().Replace("-", "") +
Path.GetExtension(vm.ImageFile.FileName);
vm.ImageFile.SaveAs(Server.MapPath("/Images/CourseImage/Images/" + vm.CourseImage));
ImageResizer img = new ImageResizer();
img.Resize(Server.MapPath("/Images/CourseImage/Images/" + vm.CourseImage),
Server.MapPath("/Images/CourseImage/Thumb/" + vm.CourseImage));
var course = new Course();
Mapper.Map(vm, course);
course.Remained = vm.Copacity;
course.CreateDate = DateTime.Now;
db.Course.Add(course);
}
db.SaveChanges();
return RedirectToAction("Index", "Course");
}
}

create new record via multiple model in one view

I have faced a problem which is can't save the record into the database. I have 3 model in one view. I have done the view and getting error about this
An exception of type 'System.Data.Entity.Validation.DbEntityValidationException' occurred in EntityFramework.dll but was not handled in user code
Additional information: Validation failed for one or more entities.
See 'EntityValidationErrors' property for more details.
here is my view
<div class="container">
<div class="row">
<div class="col-lg-12 management-title">
<h1>Create New Invoice</h1>
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<form>
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.CompanyID, "CompanyID",new { #Name="CompanyID"})
#Html.DropDownList("CompanyID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.CompanyID , "", new { #class = "text-danger" })
</div>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#bill_to_company">Company Details</a>
</h4>
</div>
<div id="bill_to_company" class="panel-collapse collapse in wrapper-company-details">
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.CompanyName)
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.CompanyName, new { #class = "form-control" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.CompanyAddress)
#Html.TextAreaFor(model => model.PurchaseInvoiceTable.CompanyAddress, new { #class = "form-control golbal_textarea" })
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.startdate)
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.startdate, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
</div>
<div class="form-group">
</div>
</div>
</div>
</div>
</div>
<h2>Product List</h2>
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#product_list">Product List</a>
</h4>
</div>
<div id="product_list" class="panel-collapse collapse in input_fields_wrap">
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel panel-default product_wrapper">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#product' + x + '">Product</a>
</h4>
</div>
<div id="product'+x+'" class="panel-collapse collapse in">
<div class="panel-group">
<div class="panel panel-default">
<div class="col-lg-12">
<div class="col-lg-3">
<label>Product</label>
#Html.TextAreaFor(model => model.PurchaseInvoiceDetailsTable.Product)
</div>
<div class="col-lg-6">
<label>Description</label>
#Html.TextAreaFor(model => model.PurchaseInvoiceDetailsTable.ProductDescription)
</div>
'<div class="col-lg-2 form-group">
<label>Price</label>
#Html.TextBoxFor(model => model.PurchaseInvoiceDetailsTable.Price)
</div>
</div>
</div>
</div>
</div>
cancel
</div>
</div>
</div>
</div>
</div>
</div>
<button class="add_field_button btn btn-primary pull-right">Add More Fields</button>
<div class="wrapper-company-details">
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.Remark)
#Html.TextAreaFor(model => model.PurchaseInvoiceTable.Remark, new { #class = "form-control", #style = "resize:none;" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.Remark, "", new { #class = "text-danger" })
</div>
<h1>Payment Term Area</h1>
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" href="#payment_term_collapse">Payment Term</a>
</h4>
</div>
<div id="payment_term_collapse" class="payment_term_area panel-collapse collapse in">
<table class="table table-bordered">
<tr style="background-color:black; color:white;">
<th style="width:70%;">
<input type="text" class="form-control" id="payment_term" placeholder="Type how many terms client want" />
</th>
<th style="width:30%;">
<button class="btn btn-default" id="add_payment_terms">Add</button>
</th>
</tr>
</table>
<table class="table table-bordered">
<tr style="background-color:black; color:white;">
<th style="width:70%;">
Payment Term
</th>
<th style="width:30%;">
Amount
</th>
</tr>
<tr style="background-color:black; color:white;">
<th style="text-align:right;">
Discount
</th>
<th>
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.Discount, new { #class = "form-control discount price_textbox", #id = "discount", #Value = "0" })
</th>
</tr>
<tr style="background-color:black; color:white;">
<th style="text-align:right;">
Total
</th>
<th>
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.Subtotal, new { #class = "form-control price_textbox total", #id = "totval", #Value = "0" })
</th>
</tr>
</table>
<div id="payment_term_area">
<h2>Payment Terms</h2>
<div class="payment_term_wrapper" style="padding:0; margin:0;">
<table class="table table-bordered" style="width:95%;">
<tr style="background-color:black; color:white;" class="payment_term_wrapper">
<th style="width:70%;">
<input class="pull-right payment_terms_label_input" style="background-color:black; color:white;"></input>
</th>
<th style="width:30%;">
#Html.TextBoxFor(model => model.PaymentTerm.Amount)
</th>
</tr>
X
</table>
</div>
</div>
<table class="table table-bordered">
<tr style="background-color:black; color:white;">
<th style="text-align:right; width:70%;">
Last Payment
</th>
<th style="width:30%;">
#Html.TextBoxFor(model => model.PurchaseInvoiceTable.Total, new { #class = "form-control price_textbox", #id = "lastpayment", #Value = "0" })
</th>
</tr>
</table>
</div>
</div>
</div>
</div>
<div class="col-lg-12">
</div>
<div class="col-lg-12">
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.Category, "Category")
#Html.DropDownList("Category", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.Category, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.Method)
#Html.DropDownListFor(model => model.PurchaseInvoiceTable.Method, new List<SelectListItem>
{
new SelectListItem() {Text = "Cash", Value="Cash"},
new SelectListItem() {Text = "Cheque", Value="Cheque"},
new SelectListItem() {Text = "Bank Transfer", Value="BankTransfer"}
}, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.Method, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.LabelFor(model => model.PurchaseInvoiceTable.PaymentTerm, "PaymentTerm", htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.PurchaseInvoiceTable.PaymentTerm, new List<SelectListItem>
{
new SelectListItem() {Text = "1", Value="1"},
new SelectListItem() {Text = "2", Value="2"},
new SelectListItem() {Text = "3", Value="3"}
}, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.PurchaseInvoiceTable.PaymentTerm, "", new { #class = "text-danger" })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.Status, new { #class = "form-control", #Value = "Active" })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.Status, new { #class = "form-control", #Value = "Active" })
#Html.HiddenFor(model => model.PaymentTerm.Status, new { #class = "form-control", #Value = "Active" })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.first_created, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.first_created, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
#Html.HiddenFor(model => model.PaymentTerm.first_created, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.first_created_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.first_created_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
#Html.HiddenFor(model => model.PaymentTerm.first_created_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.last_updated, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.last_updated, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
#Html.HiddenFor(model => model.PaymentTerm.last_updated, new { #class = "form-control", #Value = #DateTime.Now.ToString() })
</div>
<div class="form-group">
#Html.HiddenFor(model => model.PurchaseInvoiceTable.last_updated_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
#Html.HiddenFor(model => model.PurchaseInvoiceDetailsTable.last_updated_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
#Html.HiddenFor(model => model.PaymentTerm.last_updated_by, new { #class = "form-control", #Value = #Session["Username"].ToString() })
</div>
<div class="form-group">
<div>
<input type="submit" value="Create" class="btn btn-primary pull-right" />
#Html.ActionLink("Back", "Index", null, new { #class = "btn btn-small btn-danger pull-right", #style = "margin-right:2%;" })
</div>
</div>
</div>
</form>
}
</div>
</div>
here is my controller
public ActionResult Create()
{
ViewBag.CompanyID = new SelectList(db.SupplierTables, "SupplierID", "SupplierID");
ViewBag.Product = new SelectList(db.ProductTables, "ProductID", "ProductID");
ViewBag.Category = new SelectList(db.CategoryTables, "CategoryID", "CategoryID");
ViewBag.PaymentTerm = new SelectList(db.PaymentTerms, "TermID", "TermID");
return View();
}
[HttpPost]
public ActionResult Create([Bind(Include = "PurchaseInvoiceTable,PurchaseInvoiceDetailsTable,PaymentTerm")]InvoiceWrapper model)
{
if (ModelState.IsValid)
{
db.PurchaseInvoiceTables.Add(model.PurchaseInvoiceTable);
db.PurchaseInvoiceDetailsTables.Add(model.PurchaseInvoiceDetailsTable);
db.PaymentTerms.Add(model.PaymentTerm);
db.SaveChanges();
//model.PurchaseInvoiceTable.PurchaseInvoiceID = model.PurchaseInvoiceDetailsTable.InvoiceID = model.PaymentTerm.InvoiceID;
return RedirectToAction("Index");
}
ViewBag.CompanyID = new SelectList(db.SupplierTables, "SupplierID", "SupplierID");
ViewBag.Product = new SelectList(db.ProductTables, "ProductID", "ProductID");
ViewBag.Category = new SelectList(db.CategoryTables, "CategoryID", "CategoryID");
ViewBag.PaymentTerm = new SelectList(db.PaymentTerms, "TermID", "TermID");
return View(model);
}
The exception you are getting means that one or more of the entities properties that you are trying to save is not valid. e.g. The column is defined as not null and the property you are trying to save is null.
In order to see the validation errors you can use this:
catch (DbEntityValidationException dbEx)
{
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation("Property: {0} Error: {1}",
validationError.PropertyName,
validationError.ErrorMessage);
}
}
}
credits

Adding roles in the create user view ASP Identity MVC

I´m writing a project to manage a pool of users of asp.net identity 2.0, and i want to create a user and add roles to the user in the same view, so when i post the model just simple create the user and add the roles in the same action.
I don't know how to generate the roles list for the user, for example i have a dropdownlist for with the roles and id´s and my view is something like this
<div class="form-horizontal">
<div class="col-md-6">
<div class="panel panel-info">
<div class="panel-heading">Datos personales</div>
<div class="panel-body">
<div class="form-group">
<div class="col-md-4">
#Html.DisplayNameFor(m => m.User.Nombre)
</div>
<div class="col-md-8">
#Html.TextBoxFor(m => m.User.Nombre, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-4">
#Html.DisplayNameFor(m => m.User.Apellido)
</div>
<div class="col-md-8">
#Html.TextBoxFor(m => m.User.Apellido, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-4">
#Html.DisplayNameFor(m => m.User.DependenciaId)
</div>
<div class="col-md-8">
#Html.DropDownListFor(m => m.User.DependenciaId, new SelectList(ViewBag.ListaDependencia, "Id", "Descripcion"), "Ninguno", new { #class = "form-control" })
</div>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="panel panel-info">
<div class="panel-heading">Datos usuario</div>
<div class="panel-body">
<div class="form-group">
<div class="col-md-4">
#Html.DisplayNameFor(m => m.User.UserName)
</div>
<div class="col-md-8">
#Html.TextBoxFor(m => m.User.UserName, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
<div class="col-md-4">
#Html.DisplayNameFor(m => m.User.NetUser)
</div>
<div class="col-md-8">
#Html.TextBoxFor(m => m.User.NetUser, new { #class = "form-control" })
</div>
</div>
</div>
</div>
</div>
<div class="panel panel-info">
<div class="panel-heading">Datos usuario</div>
<div class="panel-body">
<div class="form-group">
<div class="col-md-4">
#Html.DisplayNameFor(m => m.User.Roles)
</div>
<div class="col-md-8">
#Html.DropDownListFor(m => m.User.Roles, new SelectList(ViewBag.RolesList, "Id", "Name"), "Ninguno", new { #class = "form-control" })
</div>
</div>
<table>
Here must present the roles to add to the user
</table>
</div>
</div>
I found a way
first a helper for offline collections, that a i found on internet
public static class HtmlPrefixScopeExtensions
{
private const string idsToReuseKey = "__htmlPrefixScopeExtensions_IdsToReuse_";
public static IDisposable BeginCollectionItem(this HtmlHelper html, string collectionName)
{
if (html.ViewData["ContainerPrefix"] != null)
{
collectionName = string.Concat(html.ViewData["ContainerPrefix"], ".", collectionName);
}
var idsToReuse = GetIdsToReuse(html.ViewContext.HttpContext, collectionName);
var itemIndex = idsToReuse.Count > 0 ? idsToReuse.Dequeue() : Guid.NewGuid().ToString();
var htmlFieldPrefix = string.Format("{0}[{1}]", collectionName, itemIndex);
html.ViewData["ContainerPrefix"] = htmlFieldPrefix;
// autocomplete="off" is needed to work around a very annoying Chrome behaviour whereby it reuses old values after the user clicks "Back", which causes the xyz.index and xyz[...] values to get out of sync.
html.ViewContext.Writer.WriteLine("<input type=\"hidden\" name=\"{0}.index\" autocomplete=\"off\" value=\"{1}\" />", collectionName, html.Encode(itemIndex));
return BeginHtmlFieldPrefixScope(html, htmlFieldPrefix);
}
public static IDisposable BeginHtmlFieldPrefixScope(this HtmlHelper html, string htmlFieldPrefix)
{
return new HtmlFieldPrefixScope(html.ViewData.TemplateInfo, htmlFieldPrefix);
}
private static Queue<string> GetIdsToReuse(HttpContextBase httpContext, string collectionName)
{
// We need to use the same sequence of IDs following a server-side validation failure,
// otherwise the framework won't render the validation error messages next to each item.
var key = idsToReuseKey + collectionName;
var queue = (Queue<string>)httpContext.Items[key];
if (queue == null)
{
httpContext.Items[key] = queue = new Queue<string>();
var previouslyUsedIds = httpContext.Request[collectionName + ".index"];
if (!string.IsNullOrEmpty(previouslyUsedIds))
foreach (var previouslyUsedId in previouslyUsedIds.Split(','))
queue.Enqueue(previouslyUsedId);
}
return queue;
}
private class HtmlFieldPrefixScope : IDisposable
{
private readonly TemplateInfo templateInfo;
private readonly string previousHtmlFieldPrefix;
public HtmlFieldPrefixScope(TemplateInfo templateInfo, string htmlFieldPrefix)
{
this.templateInfo = templateInfo;
previousHtmlFieldPrefix = templateInfo.HtmlFieldPrefix;
templateInfo.HtmlFieldPrefix = htmlFieldPrefix;
}
public void Dispose()
{
templateInfo.HtmlFieldPrefix = previousHtmlFieldPrefix;
}
}
then using an editor template
<tr>
#using (Html.BeginCollectionItem("ListaObraSocialPrepagasSeleccionadas"))
{
<td>
<input type="radio" name="RolesUserTableRadio" />
#Html.HiddenFor(model => model.Id, new { #readonly = "readonly" })
</td>
<td>
#Html.HiddenFor(model => model.Id, new { #readonly = "readonly" })
#Html.DisplayTextFor(model => model.Name)
</td>
}
a partial view to manage the list
<script type="text/javascript">
$(document).ready(function () {
$("#btnAddRoles").click(function () {
var rolId = $("#ddRoles").val();
if (rolId == null || rolId == '') {
alert("Debe seleccionar un rol.");
return;
}
var foundRol = $("#RolesUserTable").find("input[value='" + rolId + "']");
if (foundRol.size() > 0) {
alert("Ya se ha agregado el rol.");
return;
}
$.ajax({
url: '#Url.Action("AddRoles", "Users")',
data: {
rolId: rolId
},
type: 'GET',
contentType: 'application/x-www-form-urlencoded',
success: function (data) {
if (data.Valid) {
$("#RolesUserTable").append(data.html);
} else {
alert('El rol seleccionado no existe');
}
},
error: function (jqXHR, exception) {
alert('Error durante la llamada al servidor.' + jqXHR.responseText);
},
complete: function () {
}
});
});
$("#btnDeleteRoles").click(function () {
var myRadio = $('input[name=RolesUserTableRadio]');
var radio = myRadio.filter(':checked');
if (radio.size() == 0) {
alert("Debe seleccionar un rol.");
return;
}
if (!confirm("¿Confirma que desea eliminar el rol seleccionado?")) {
return;
}
$(radio).closest('tr').remove();
});
});
</script>
<div style="width: 100%; overflow-x: auto;">
<table id="RolesUserTable" class="table table-striped">
<thead>
<tr>
<th></th>
<th>Rol</th>
</tr>
</thead>
#Html.EditorFor(m => m.Roles)
</table>
</div>
and finnaly the dropdown and the table
<div class="form-group">
<label for="ddRoles" class="col-sm-2 control-label">Roles</label>
<div class="col-sm-3">
#Html.DropDownList("ddRoles", new SelectList(ViewBag.Roleslist, "Id", "Name", null), "Seleccione un rol", new { #class = "selectpicker", data_live_search = "true" })
</div>
<div class="btn-group">
<button id="btnAddRoles" type="button" class="btn btn-default"><span class="glyphicon glyphicon-plus"></span></button>
<button id="btnDeleteRoles" type="button" class="btn btn-default"><span class="glyphicon glyphicon-minus"></span> </button>
</div>
</div>
<div>
#Html.Partial("_Roles")
</div>

Categories