Using RadioButtonFor and CheckBoxFor in nested for loops (razor syntax) - asp.net-mvc

My code looks like the following:
#for (var i = 0; i < Model.Count; i++)
{
<h2>Question #Html.DisplayFor(x => x[i].OrderIndex) </h2>
#Html.HiddenFor(x => x[i].SurveyId)
#Html.HiddenFor(x => x[i].QuestionId)
#Html.HiddenFor(x => x[i].AnswerId)
<br />
#Html.DisplayFor(x => x[i].QuestionText)
<br />
#Html.DisplayFor(x => x[i].QuestionText)
#if (Model[i].Type == QuestionType.Single)
{
<h2>Answer</h2>
#for (var ao = 0; ao < Model[i].Answer.AnswerOptions.Count; ao++)
{
#Html.RadioButtonFor(x => x[i].Answer.AnswerOptions[ao].IsSelectedAnswer, true) #Html.Raw(" ");
#Html.LabelFor(x => x[i].Answer.AnswerOptions[ao].IsSelectedAnswer, Model[i].Answer.AnswerOptions[ao].OptionText)<br />
#Model[i].Answer.AnswerOptions[ao].OptionText
}
}
}
I can get every other control type to work ok, but I'm not sure how to wire up radio buttons with my model. It's in a nested for loop.
I've also tried:
#Html.RadioButtonFor(x => x[i].Answer.AnswerOptions[ao].IsSelectedAnswer, Model[i].Answer.AnswerOptions[ao].OptionText)
#Html.Raw(" ");
This should get the value, but it does not. Also, I can't get displayfor or labelfor working:
#Html.LabelFor(x => x[i].Answer.AnswerOptions[ao].IsSelectedAnswer, Model[i].Answer.AnswerOptions[ao].OptionText)
<br />

Related

How to submit only one item from a list

I have a list of objects and i want to be able to do is when a user clicks the button associated with an item from the list, that item is displayed in another view
#model VitalBits_2._0.Models.VitalBitListModel
<html>
<head>
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
</script>
</head>
<body>
<table>
<tr>
<th style="align-content:center">
Title
</th>
<th style="align-content:center">
Vital Bit Type
</th>
<th>
</th>
</tr>
#for (int i = 0; i < Model.VitalBitList.Count; i++)
{
using (Html.BeginForm("PopulateEdit_Create", "Configuration", FormMethod.Post))
{
<tr>
<td style="align-content:center">
#Html.HiddenFor(x => Model.VitalBitList[i].ID)
#Html.DisplayFor(x => Model.VitalBitList[i].Title)
#Html.HiddenFor(x => Model.VitalBitList[i].Title)
</td>
<td style="align-content:center">
#Html.DisplayFor(x => Model.VitalBitList[i].Message)
#Html.HiddenFor(x => Model.VitalBitList[i].Message)
#Html.HiddenFor(x => Model.VitalBitList[i].IsActive)
#Html.HiddenFor(x => Model.VitalBitList[i].IsPriority)
#Html.HiddenFor(x => Model.VitalBitList[i].BitType)
#Html.HiddenFor(x => Model.VitalBitList[i].Created)
#Html.HiddenFor(x => Model.VitalBitList[i].CreatedBy)
#Html.HiddenFor(x => Model.VitalBitList[i].LastModified)
#Html.HiddenFor(x => Model.VitalBitList[i].LastModifiedBy)
</td>
<td>
<button type="submit">Edit</button>
</td>
</tr>
}
}
</table>
<div id="CreateEdit"></div>
</body>
This is how my code currently stands but i am currently getting my constructor values instead of the item selected
[HttpPost]
public ActionResult PopulateEdit_Create(VitalBit selectedItem) {
DataFactory dataFactory = new DataFactory();
//Logic and stuff
return View("~/Views/Configuration/Create_Edit.cshtml", selectedItem);
}
In other words can i only submit one item to my controller at a time, or do i have to do it in a different way?
Any help would be appreciated

Returning specific table data from the view to the controller? asp.net MVC

So I have a view which is currently displaying a table of data from the database with a select/selectall checkbox in place. What I'd like to do is be able to get a list of my CustomerNumbers and whether or not they have been checked and return it to my controller for further action.
Below is my how my view is currently written. I have tried numberous ways to get this to work and I am stumped.
#model MassInactiveInspections.Models.CustomerInfoList
<div class="container">
<h2>#ViewBag.Title</h2>
<div class="bs-callout bs-callout-info" style="margin-bottom: 0px;">
</div>
<div class="col-md-8">
#using (Html.BeginForm("SelectedCustomers", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
<table class="table table-bordered">
<tr>
<th class="active">#Html.DisplayName("Select All?")<input type="checkbox" class="select-all checkbox" name="select-all" /></th>
<th>#Html.DisplayNameFor(m => m.CustomerInfoListView.FirstOrDefault().BusinessName)</th>
<th>#Html.DisplayNameFor(m => m.CustomerInfoListView.FirstOrDefault().CustomerName)</th>
<th>#Html.DisplayNameFor(m => m.CustomerInfoListView.FirstOrDefault().CustomerNumber)</th>
<th>#Html.DisplayNameFor(m => m.CustomerInfoListView.FirstOrDefault().InspectionCycleDescription)</th>
<th>#Html.DisplayNameFor(m => m.CustomerInfoListView.FirstOrDefault().LastInspectionDate)</th>
<th>#Html.DisplayNameFor(m => m.CustomerInfoListView.FirstOrDefault().RouteCode)</th>
<th>#Html.DisplayNameFor(m => m.CustomerInfoListView.FirstOrDefault().RouteID)</th>
<th>#Html.DisplayNameFor(m => m.CustomerInfoListView.FirstOrDefault().SiteNumber)</th>
<th>#Html.DisplayNameFor(m => m.CustomerInfoListView.FirstOrDefault().SystemCode)</th>
</tr>
#foreach (var item in Model.CustomerInfoListView)
{
<tr>
<td class="active"> <input id="Selected" input type="checkbox" class="select-item checkbox" name="select-item" value="1000" /> </td>
<td>#Html.DisplayFor(modelItem => item.BusinessName)</td>
<td>#Html.DisplayFor(modelItem => item.CustomerName)</td>
<td>
#Html.DisplayFor(modelItem => item.CustomerNumber)
#Html.HiddenFor(m => m.CustomerInfoListView.FirstOrDefault().CustomerNumber)
</td>
<td>#Html.DisplayFor(modelItem => item.InspectionCycleDescription)</td>
<td>#Html.DisplayFor(modelItem => item.LastInspectionDate)</td>
<td>#Html.DisplayFor(modelItem => item.RouteCode)</td>
<td>#Html.DisplayFor(modelItem => item.RouteID)</td>
<td>#Html.DisplayFor(modelItem => item.SiteNumber)</td>
<td>#Html.DisplayFor(modelItem => item.SystemCode)</td>
</tr>
}
</table>
</div>
<div class="form-group">
<div style="margin-top: 50px">
<input type="submit" id="btnLost" class="btn btn-primary" value="Lost"/>
<input type="submit" class="btn btn-primary" name="OOBButton" value="OOB" />
<input type="submit" class="btn btn-primary" name="RefusedButton" value="Refused" />
</div>
</div>
}
</div>
</div>
and finally my controller
[HttpPost]
public ActionResult SelectedCustomers(CustomerInfoList
customerNumberList)
{
return View("ViewCustomerInfo");
}
also here is my javascript for the checkboxes
[HttpPost]
public ActionResult SelectedCustomers(CustomerInfoList customerNumberList)
{
return View("ViewCustomerInfo");
}
//column checkbox select all or cancel
$("input.select-all").click(function () {
var checked = this.checked;
$("input.select-item").each(function (index, item) {
item.checked = checked;
});
});
//check selected items
$("input.select-item").click(function () {
var checked = this.checked;
console.log(checked);
checkSelected();
});
//check is all selected
function checkSelected() {
var all = $("input.select-all")[0];
var total = $("input.select-item").length;
var len = $("input.select-item:checked:checked").length;
console.log("total:" + total);
console.log("len:" + len);
all.checked = len === total;
}
});
Not sure if it is the best way to handle it but I simply added the fields that I wanted into a HiddenFor helper and they were returned to my the appropriate controller. Thanks everyone for the help.
#Html.HiddenFor(m => m.additionalCustomerInfoListView[i].CustomerNumber)

#Html.HiddenFor returning null value

I am trying to return the results of a table back to the controller for further manipulation. Once returned to the controller the value shows as null. In the past I have been able to use #Html.HiddenFor to return the values but it doesn't seem to be working in this instance. Not sure what I am doing wrong here. Any help is greatly appreciated.
#model IEnumerable<Project.Models.Item>
#{
ViewBag.Title = "Welcome to The Project";
}
#using (Html.BeginForm("UpdateQuality", "Home", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
<div class="row">
<div class="form-group">
<table class="table table-bordered">
<tr>
<th>#Html.DisplayNameFor(m => m.Name)</th>
<th>#Html.DisplayNameFor(m => m.SellIn)</th>
<th>#Html.DisplayNameFor(m => m.Quality)</th>
</tr>
#for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>#Html.DisplayFor(m => m.ElementAt(i).Name)</td>
<td>#Html.DisplayFor(m => m.ElementAt(i).SellIn)</td>
<td>#Html.DisplayFor(m => m.ElementAt(i).Quality)</td>
#Html.HiddenFor(m => m.ElementAt(i).Name)
#Html.HiddenFor(m => m.ElementAt(i).SellIn)
#Html.HiddenFor(m => m.ElementAt(i).Quality)
</tr>
}
</table>
<div class="form-group">
<div style="margin-top: 50px">
<input type="submit" class="btn btn-primary" value="Advance Day"/>
</div>
</div>
</div>
</div>
}
And here is the controller which returns null.
public ActionResult UpdateQuality(List<Item> Items )
{
return View("Index", (object)Items);
}
You cannot use ElementAt() in a HtmlHelper method that generates form controls (look at the name attribute your generating - it does not match your model).
Either change the model to be IList<T>
#model List<Project.Models.Item>
and use a for loop
#for (int i = 0; i < Model.Count; i++)
{
....
#Html.HiddenFor(m => m.[i].Name)
....
or change use a custom EditorTemplate for typeof Item, and in the main view, use #Html.EditorFor(m => m) to generate the correct html for each item in the collection.

Send single value through RouteValueDictionary

One of the properties of my ViewModel is an array which, unfortunately, is null every time I post back to the controller. I figured a simple hack where I place the values into a coma-delimited string.
This works great for our paging plugin, which posts back to our Index method, using a RouteValueDictionary. However, it is not working in the Html.BeginForm helper which posts back to a different controller action (the Update method).
View
#*Since we can't send arrays or complex objects break array down into string for RouteValueDictionary*#
var channelCodes = "";
for (int i = 0; i < Model.searchChannelCode.Length; i++)
{
channelCodes += Model.searchChannelCode[i];
if (i + 1 < Model.searchChannelCode.Length)
{
channelCodes += ",";
}
}
#*The 'searchChannelCodesPagin' variable from this RouteValueDictionary always posts back as null
using (Html.BeginForm("Update", "ZipCodeTerritory", new RouteValueDictionary()
{
{"searchChannelCodesPaging", channelCodes }
}, FormMethod.Post, new {id = "UpdateForm"}))
{
#Html.HiddenFor(model => model.searchZip)
#Html.HiddenFor(model => model.searchTerritory)
#Html.HiddenFor(model => model.searchState)
#Html.HiddenFor(model => model.searchActiveOnly)
#Html.HiddenFor(model => model.zipCodeTerritory)
<div id="cloneBox">
<div id="rw1">
#Html.LabelFor(model => model.newTerritory)
#Html.TextBoxFor(model => model.newTerritory, new { style = "width: 30px;padding-left:10px;", maxLength = 3 })
#Html.LabelFor(model => model.newDescription)
#Html.TextBoxFor(model => model.newDescription, new { style = "width: 250px;padding-left:10px;", maxLength = 30 })
#Html.LabelFor(model => model.newEffectiveDate)
#Html.TextBoxFor(model => model.newEffectiveDate, new { style = "width: 80px;padding-left:10px;" })
<div id="rw2" style="padding-top: 10px;">
#Html.LabelFor(model => model.newChannelCode)
#Html.DropDownListFor(model => model.newChannelCode, Model.ChannelCodes, " ")
#Html.LabelFor(model => model.newStateCode)
#Html.DropDownListFor(model => model.newStateCode, Model.StateCodes, " ")
#Html.LabelFor(model => model.newEndDate)
#Html.TextBoxFor(model => model.newEndDate, new { style = "width: 80px;" })
</div>
</div>
</div>
<br/>
<div id="buttonDiv">
<button type="submit" id="CloneButton" name="button" value="clone">Apply New Data</button>
<button type="submit" id="deleteButton" name="button" value="delete">Delete Selected Items</button>
<button type="submit" id="removeButton" name="button" value="removeErrors">Remove Selected Errors</button>
</div>
}
Controller
The forma above posts to this controller action. The searchChannelCodePaging variable is null each time.
[HttpPost]
public ActionResult Update(ZipCodeIndex updateZip, string button, string searchChannelCodesPaging)
{
Since you are doing a post, the simplest way to get it to the backend would be add a hidden field:
#Html.HiddenFor("searchChannelCodesPaging", searchChannelCodesPaging);
As a routing value, you may need to get it explicitly within the control via one of the two following approaches. These objects are directly accessible within the Controller class.
RouteData.Values("searchChannelCodesPaging")
Request.QueryString.Get("searchChannelCodesPaging");
You don't have to serialize a array type model parameter to a CSV string to get it to post to your controller. You can do this instead:
#for (var i = 0; i < Model.searchChannelCode.Length; i++)
{
#Html.HiddenFor(m => m.searchChannelCode[i]);
}

MVC 4 binding nested list of lists result

I've done some research on this and seem to find posts that are either outdated or don't quite work in my situation. I may be using wrong keywords when searching though... =/
On my web page I have Tabs containing Group boxes that contain Lines which in turn contain Items.
So it is lists of lists 4 levels.
The problem:
When posting back, ViewModel.Tabs is null and I can't save anything.
Everything displays quite nicely, but nothing is posted back.
The code
Views/Shared/EditorTemplates/Tab.cshtml
#model AWMCCRM.Web.ViewModels.Tab
#Html.HiddenFor(vm => vm.Name)
<div id="tab-#Model.Name.Replace(" ", string.Empty)" class="tab-content two">
#Html.EditorFor(vm => vm.Groups)
</div>
Views/Shared/EditorTemplates/Group.cshtml
#model AWMCCRM.Web.ViewModels.Group
#Html.HiddenFor(vm => vm.Name)
<fieldset>
<legend>#Model.Name</legend>
#Html.EditorFor(vm => vm.Lines)
</fieldset>
Views/Shared/EditorTemplates/Line.cshtml
#model AWMCCRM.Web.ViewModels.Line
<div class="_100Max">
#Html.HiddenFor(vm => vm.Name)
#Html.EditorFor(vm => vm.Items)
</div>
Views/Shared/EditorTemplates/Item.cshtml
#model AWMCCRM.Web.ViewModels.Item
<div class="_#Model.DisplaySize" title="#Model.Description">
<p>
#Html.HiddenFor(x => x.DataType)
#Html.HiddenFor(x => x.Description)
#Html.HiddenFor(x => x.DisplaySize)
#Html.HiddenFor(x => x.DisplayType)
#Html.HiddenFor(x => x.IDsPiped)
#Html.HiddenFor(x => x.ItemType)
#Html.HiddenFor(x => x.Name)
#Html.LabelFor(vm => vm.Value, Model.Name)
#switch (Model.DisplayType.ToLower().Replace(" ", string.Empty))
{
case "checkbox":
#Html.CheckBoxFor(vm => Convert.ToBoolean(vm.Value))
break;
case "dropdownlist":
#Html.DropDownListFor(vm => vm.Value, Model.ValueOptionListItems)
break;
case "multiselectlist":
#Html.ListBoxFor(
x => x.SelectedValueList,
Model.ValueOptionListItems,
new { id = "itemValuesMultiSelect", multiple = "multiple", Size = 15 })
break;
case "radiobutton":
#Html.RadioButtonFor(vm => vm.Value, Model.Value)
break;
case "textarea":
#Html.TextAreaFor(vm => vm.Value)
break;
default:
#Html.TextBoxFor(vm => vm.Value)
break;
}
</p>
</div>
The ViewModel (cut down version)
namespace AWMCCRM.Web.ViewModels
{
public class PersonEditViewModel
{
public List<Tab> Tabs { get; set; }
//Other properties
//...
}
}
The View (cut down version)
#using (Html.BeginForm("Edit", "Person", FormMethod.Post, new { id = "validate-form", #class = "block-content form" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(x => x.PersonID)
#foreach (var tab in Model.Tabs)
{
#Html.EditorFor(vm => tab)
}
<input class="close-toolbox button" type="submit" value="Save">
}
Any suggestions?
Thanks
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
It's an old article, but it still applies.
I had this exact problem, but basically due to the model binding system you need to use an explicit for loop instead of a foreach loop, and reference your elements by their index.
#using (Html.BeginForm("Edit", "Person", FormMethod.Post, new { id = "validate-form", #class = "block-content form" }))
{
Html.AntiForgeryToken()
Html.HiddenFor(x => x.PersonID)
for (int i = 0; i<Model.Tabs.Count; i++)
{
Html.EditorFor(x => Model.Tabs[i])
}
<input class="close-toolbox button" type="submit" value="Save">
}

Resources