DropdownlistFor in a loop, null model on submit - asp.net-core-mvc

I am having an issue with the values selected in multiple dropdownlistfor(s) being available in the controller when the form is submitted. The model is always blank. I know there are issues with mvc having dropdowns in loops but I thought I have solved for this. Let me know what you think.
View
#model DataDictionaryConversion.Models.FinalResults
#{ using (Html.BeginForm("SaveMapping", "Home", FormMethod.Post, null))
{
#Html.AntiForgeryToken()
<table class="table table-striped">
<thead>
<tr>
<th>Converted to Name</th>
<th>Your Project Name</th>
<th><input type="button"
onclick="checkAll()"/></th>
</tr>
</thead>
<tbody>
#{for (int x = 0; x < Model.DDObjects.Count(); x++)
{
var isSelection = false;
<tr>
<td class="filterable-cell">#Model.DDObjects[x].ObjectName</td>
<td class="filterable-cell">
#Html.DropDownList(Model.DDObjects[x].ObjectName, new
SelectList(Model.ProjectObjects, "ObjectName", "ObjectName"),
htmlAttributes: new { #id = "ddlObject", #class = "js-example-basic-single" })</td>
</td>
<td>
<input type="checkbox" id="NoValue-
#Model.DDObjects[x].ObjectName" name="NoValue-
#Model.DDObjects[x].ObjectName" onclick="byPassObject(this)" /> Object
Not
Used
</td>
</tr>
}
}
</tbody>
<tfoot>
<tr>
<td style="text-align:right; height:20px"><input
type="submit" class="btn btn-warning" value="Generate Conversion Mapping"
/></td>
</tr>
</tfoot>
</table>
}
}
Controller
[HttpPost]
public ActionResult SaveMapping([FromServices]ApplicationDbContext context, FinalResults model)
{
return View("Mapping");
}
Model
public class FinalResults
{
public IList<FinalObjectModel> ProjectObjects { get; set; }
public IList<Conversion_CSD_ObjectNameLearningModel> DDObjects {
get; set; }
FinalResults model is null

You're using Html.DropDownList. The first param there is a string, which should correspond with the name you're binding to. However, you're passing the value of Model.DDObjects[x].ObjectName, not literally something like "DDOjbects[0].ObjectName".
Instead, you should be using Html.DropDownListFor like so:
#Html.DropDownListFor(m => m.DDObjects[x].ObjectName, ...)
Then, the select list will be bound correctly.

Related

IEnumerable Model from view to Controller is NULL [duplicate]

This question already has answers here:
Post an HTML Table to ADO.NET DataTable
(2 answers)
Closed 4 years ago.
I am trying to return table values of my view back to the controller to save on db but I keep getting null. I can post the values without problem and bind them to the view.
I cannot understand why, I am using a server side view model.
Is there any way to perform this?
View:
#model IEnumerable<MultiEdit.Models.TableViewModel>
#using (Ajax.BeginForm("Save", "UUTs", new AjaxOptions
{
HttpMethod = "Post",
}, new { id = "tableForm" }))
{
#Html.AntiForgeryToken()
<div class="row" style="padding-top:10px;">
<div class="col-lg-12">
<table class="table table-bordered table-striped ">
<thead>
<tr>
<th>
#Html.DisplayNameFor(model => model.IsChassis)
</th>
<th>
#Html.DisplayNameFor(model => model.Justification)
</th>
</tr>
</thead>
<tbody id="tblMultiEdit">
#foreach(var item in Model)
{
<tr>
<td>
#Html.CheckBoxFor(modelItem => item.CheckIsChassis)
</td>
<td>
#Html.EditorFor(modelItem => item.Justification)
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
}
Controller:
public void Save(IEnumerable<TableViewModel> vm)
{
DoSomething();
}
You need to iterate through your collection with a for loop and index qualifier. Something like the below. The syntax is not exact but you should be able to see what I mean.
#for(var index = 0; index <= Model.Count - 1; index++)
{
<tr>
<td>
#Html.CheckBoxFor(modelItem => Model[index].CheckIsChassis)
</td>
<td>
#Html.EditorFor(modelItem => Model[index].Justification)
</td>
</tr>
}
This is required so the index can be used to create the unique id's of the Enumerable items and aids model binding
Hope that helps
I resolved it by using IList insead of IEnumerable.
View:
#model IList<MultiEdit.Models.TableViewModel>
#Html.CheckBoxFor(modelItem => modelItem[index].CheckIsChassis, new { #class = "form-control" })
Controller:
public void Save(IList<TableViewModel> vm)
{
var x = vm;
}

'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' 'object' does not contain a definition for 'intEmployeeId'

I am getting an exception when i trying to display the values of viewbag. I have joined two tables and stored that data in viewbag using Linq.
This is my controller action method
public ActionResult HRSeparationDetails()
{
//List<trnEsSeparationDetail> separationlist = (from list in db.trnEsSeparationDetails
// select list).ToList();
ViewBag.SeparationList = (from list in db.trnEsSeparationDetails
join R in db.mstEsEmpReasonForSeparations
on list.ReasonForSeperationId equals R.intSeperationId
select new
{
intEmployeeId = list.intEmpId,
ReasonForSeparation = R.txtReasonForSeperation,
ResiganationDate = list.dtResignationDate,
RelievingDate = list.dtRequestedRelievingDate,
SeparationRemarks = list.txtRemark
}).ToList();
return View();
}
This is my viewpage
#model IEnumerable<EMPApp.Models.trnEsSeparationDetail>
#{
ViewBag.Title = "HRSeparationDetails";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>HRSeparationDetails</h2>
<div>
#if (ViewBag.SeparationList == null)
{
<div style="color:green"><h3>#ViewBag.SeparationerrorMessage</h3></div>
}
else
{
<table class="grid" cellpadding="0" cellspacing="0">
<tr>
<th>
<b>Employee Id</b>
</th>
#*<th>
<b>ReasonForSeparationId</b>
</th>*#
<th>
<b>Reason For Separation</b>
</th>
<th>
<b>Resignation Date</b>
</th>
<th>
<b>Relieving Date</b>
</th>
<th>
<b>Separation Remarks</b>
</th>
</tr>
#foreach (var item in ViewBag.SeparationList)
{
<tr>
<td>
#item.intEmployeeId
#*#{
Session["SeparationEmpId"] = item.intEmpId;
}
#Html.ActionLink(Session["SeparationEmpId"].ToString(), "EmployeeDashboard", "HRAdmin", new { id = #item.intEmpId }, null)*#
</td>
#*<td>
#item.ReasonForSeperationId
</td>*#
<td>
#item.ReasonForSeparation
</td>
<td>
#item.ResiganationDate
</td>
<td>
#item.RelievingDate
</td>
<td>
#item.SeparationRemarks
</td>
</tr>
}
</table>
}
Any help will be appreciated. Thanks..
ViewBag is a dynamic object and your setting the property to a collection of anonymous objects. In you foreach loop
#foreach (var item in ViewBag.SeparationList)
item is typeof object and object does not have a property intEmployeeId (or any of the other properties your define in the anonymous object). One way to handle this is to create a view model with the properties you want to display
public class SeparationDetailVM
{
public int intEmployeeId { get; set; }
public DateTime ResiganationDate { get; set; }
....
}
and in the controller
var details = (from list in ....
select new SeparationDetailVM
{
intEmployeeId = list.intEmpId,
ResiganationDate = list.dtResignationDate,
....
}).AsEnumerable();
return View(details); // no need for ViewBag
and in the view
#model IEnumerable<YourAssembly.SeparationDetailVM>
....
#foreach (var item in Model)
{
....
<td>#item.intEmployeeId</td>
<td>#item.ResiganationDate</td>
....
}

ASP.NET MVC Razor Headers and Views for Each Column Dynamically

I have the following Razor lines for now:
<table border=1 cellpadding=3 cellspacing=1 rules="rows" frame="box">
<tr>
<th>Türkçe Söz Dizisi</th>
<th>English Word Sequence</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Tr)
</td>
<td>
#Html.DisplayFor(modelItem => item.En)
</td>
<td>
#Html.ActionLink((String)#ViewBag.Edit, "Edit", new { id=item.ID }) |
#Html.ActionLink((String)#ViewBag.Delete, "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
However, I will add some columns automatically from the program to database table. I need a way to print this th's and td's accordingly. In short, I need a way to go through Model's dynamic columns. How can I achieve this?
EDIT: My Model type here is "Proposal". However, I want to reach dynamic attribute of Proposal.Type.Word(Tr, En, or any other added Language Enum). How can I?
#foreach (var item in Model) {
Type objectType = Type.GetType(typeof(RexamOneriSistemi.Models.Word).AssemblyQualifiedName);
System.Reflection.PropertyInfo[] fields = objectType.GetProperties();
<tr>
<td>#Html.DisplayFor(modelItem => item.ID)</td>
<td>#Html.DisplayFor(modelItem => item.Owner.Name)</td>
#foreach (System.Reflection.PropertyInfo f in fields) {
if (f.Name.ToString() == #HttpContext.Current.Session["Language"].ToString())
{
<td>
// What to do here exactly to get item.Type.Word.[dynamic attribute]?
</td>
}
</tr>
}
I can get Razor String
string s = "#Html.Displayfor(modelItem => item.Type.Word." + System.Web.HttpContext.Current.Session["Language"] + ")"
Resulting: #Html.Displayfor(modelItem => item.Type.Word.Tr)
Can I insert a string to be rendered as Razor Syntax? If yes, how?
I have tried this code and it works
<table border=1 cellpadding=3 cellspacing=1 rules="rows" frame="box">
<tr>
#{
Type objectType = Type.GetType(typeof(yourProjectNamespace.Models.Language).AssemblyQualifiedName);
System.Reflection.PropertyInfo[] fields = objectType.GetProperties();
foreach (System.Reflection.PropertyInfo f in fields)
{
<th> #f.Name.ToString() </th>
}
}
</tr>
#foreach (yourModelType item in Model) {
<tr>
foreach (System.Reflection.PropertyInfo f in fields)
{
<td>#Html.Display(f.Name.ToString())</td>
}
<td>
#Html.ActionLink((String)#ViewBag.Edit, "Edit", new { id=item.ID }) |
#Html.ActionLink((String)#ViewBag.Delete, "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
To get Assemply Qualified Name of your class , see this link here
Came across this question, wrote this maybe it will help someone else. This code will dynamically load your model into a table.
#model System.Collections.Generic.List<App.Client.Models.MyModel>
<table>
<thead>
<tr>
#foreach (var property in Model.GetType().GetGenericArguments()[0].GetProperties())
{
<th>#property.Name</th>
}
</tr>
</thead>
<tbody>
#foreach (var modelItem in Model)
{
<tr>
#foreach (var property in modelItem.GetType().GetProperties())
{
<td>#property.GetValue(modelItem)</td>
}
</tr>
}
</tbody>
</table>

Is there an #Html.ActionLink equivilent for HttpPost?

I have a table that I need to add links to. The links need to go to an HTTPPost actionResult on my controller. I have a huge list that the user needs to be allowed to click on the status, hit the controller and route to the appropriate page afterward. #Html.ActionLink is an HttpGet action. Is there an equivalent for a post?
<table class="table table-striped table-bordered">
<th>Ssn</th>
<th>State</th>
<th>File Uploaded Date</th>
<th>Claim Status</th>
#foreach (var currentClaim in Model.CurrentClaims)
{
<tr >
<td><span name="Ssn">#currentClaim.SSN</span></td>
<td>#currentClaim.StateName</td>
<td>#currentClaim.ClaimDate</td>
<td>#Html.ActionLink(#currentClaim.ClaimStatus, "SubmitClaim", "Claim", FormMethod.Post, new ClaimInputModel { SSN = currentClaim.SSN, StateId = currentClaim.StateId })</td>
</tr>
}
</table>
I tried using
#using("SubmitClaim", "Claim", FormMethod.Post, new ClaimInputModel { SSN = currentClaim.SSN, StateId = currentClaim.StateId })
{
<button type="submit" >xxx</button>
}
I get an HttpCompiler error with this.
You need to use the BeginForm() HtmlHelper that returns a MvcForm which implements IDisposable...
#using(Html.BeginForm("SubmitClaim", "Claim", FormMethod.Post, new { SSN = currentClaim.SSN, StateId = currentClaim.StateId }))
{
<button type="submit" >xxx</button>
}

EditorTemplate + Model not being returned on POST

I can't seem to figure this out, it is driving me crazy!
Essentially, I have a list of rows I need to display with one drop down list per row.
I have a view model:
public class UserMembershipViewModel:BaseViewModel
{
public List<ProgramMembership> ProgramMembership { get; set; }
}
In my parent view I have, as you can see I am using an editor template which is located in "/Views/Shared/EditorTemplates/ProgramMembership.cshtml":
#using AcnCS.Model
#model AcnCS.Model.ViewModels.User.UserMembershipViewModel
#{
ViewBag.PageHeader = "Membership for " + Model.User.FullName;
ViewBag.PageTitle = "Membership for " + #Model.User.FullName;
ViewBag.HideNav = true;
}
#if (Model.ProgramMembership != null)
{
<div class="row-fluid">
<div class="span12">
<div id="permissions">
#using (Html.BeginForm())
{
<table class="table table-bordered">
<thead>
<tr>
<td>Program</td>
<td>Effective Membership?</td>
<td>Permission Type</td>
</tr>
</thead>
#Html.EditorFor(m => Model.ProgramMembership, "ProgramMembership")
</table>
<input type="submit" class="btn btn-primary" value="Save Changes"/>
}
</div>
</div>
</div>
}
My Editor template (ProgramMembership.cshtml) is:
#using AcnCS.Model
#model List<AcnCS.Model.ProgramMembership>
#foreach(ProgramMembership membership in Model)
{
<tr>
<td>#membership.ProgramName</td>
<td>
#if (membership.IsMember)
{
<span class="label label-success">#membership.IsMember</span>
}
else
{
#membership.IsMember
}
</td>
<td>#Html.DropDownListFor(x => membership.PermissionType, membership.PermissionTypes)</td>
</tr>
}
Everything is being displayed properly, but when I submit, my model object is null, even the ProgramMembership property in the model is null:
[HttpPost]
public ActionResult Membership(UserMembershipViewModel model)
{
// model IS NULL!!
return View(model);
}
Any help would be greatly appreciated!
I would pluralize the Property name since it is a collection, for better readability
public class UserMembershipViewModel:BaseViewModel
{
public List<ProgramMembership> ProgramMemberships { get; set; }
}
and you dont need a Loop inside your EditorTemplate file
#model AcnCS.Model.ProgramMembership
<tr>
<td>#membership.ProgramName</td>
<td>
#if (membership.IsMember)
{
<span class="label label-success">#membership.IsMember</span>
}
else
{
#membership.IsMember
}
</td>
<td>#Html.DropDownListFor(x => membership.PermissionType, membership.PermissionTypes)</td>
</tr>
In your main view,call your EditorTemplate like this
#Html.EditorFor(m=>m.ProgramMemberships)

Resources