How to make it work without hard coding.
#foreach (var item in Model.Items)
{
//not working - it's assigning blank value
#Html.HiddenFor(o => o.ItemIds, new { #value = item.Value.ToString() })
//working
#Html.Hidden("ItemIds", item.Value);
}
You could change your Model.Items declaration from an IEnumerable to an List, then reference your item via the index like so:
#Html.HiddenFor(o => o.Items[Model.Items.IndexOf(item)].Value)
Related
Working on MVC 5 app.
I have a table with a bunch of columns. One column contains a radio button list of items. Since this is an "edit" view I need to pre-populate the selected radio button properly. (ie select the item that's in the db)
Part of my controller code...
newVmRecord.SurveyAnswerOption =
new SelectList(db.SurveyAnswerOptions,
"AnswerOptionText", "AnswerOptionText", ar.SurveyAnswer);
Here's the razor:
#foreach (SelectListItem item in
(IEnumerable<SelectListItem>)Model[i].SurveyAnswerOption)
{
#Html.RadioButtonFor(modelItem => Model[i].SelectedSurveyAnswer,
Model[i].SurveyAnswerOption, new { #Checked =
Model[i].SelectedSurveyAnswer}) #item.Text
}
The available options are 'yes', 'no' and 'n/a'. In the database, for example, if 'no' was already selected then it should be pre-selected when this view loads. The radio buttons appear correctly, but, the #Checked doesn't work correctly.
By the way, I am sure there is existing data because I put this line of code as the first line the foreach....
#Html.DisplayTextFor(modelItem => Model[i].SelectedSurveyAnswer);
Any suggestions? Thanks!
Please try this:
#foreach (SelectListItem item in (IEnumerable<SelectListItem>)Model[i].SurveyAnswerOption)
{
#Html.RadioButtonFor(modelItem => Model[i].SelectedSurveyAnswer,#item.Value, Model[i].SelectedSurveyAnswer == item.Value ? new {Checked = "checked"} : null) #item.Text
}
I have the following code in my view:
#foreach (var x in model)
{
<input type="checkbox" name="#x.name" /> #x.name
}
That loop will create about 10 check boxes with each of them having a unique name generated during the runtime. The whole point of this is to make this dynamic without me having to type the values of each name. So when I am trying to check in my controller if each of these check boxes are checked or not, how do I do it? Normally, I would pass a parameter to my controller
public ActionResult MyController(string/bool checkboxName)
and this would work fine if I had one checkbox. However, passing 10 parameters for each check box in the controller sounds insane! What if I add more to x in model later so that I have 20 check boxes?
In the loop you are creating the checkboxes, add them to an ICollection and then iterate over that collection looking for CheckBox.Checked.
I'm certain there is a helper function for that in MVC but I'm traveling and don't quite remember it. Something like this should work, adapt as needed.
Note: This assumes they are all on the same page.
#foreach (var control in this.Controls)
{
if (control is CheckBox)
{
if (((CheckBox)control).Checked)
{
//record as you need
}
}
}
I think one of the ways to do this, which might not be ideal but can still work is to use the FormCollection in the MVC framework since you are using a loop, you can loop the elements in your action
/// your view side
#foreach (var x in model)
{
<input type="checkbox" name="#x.name" /> #x.name
}
///The action side
public ActionResult MyController(FormCollection collection, YourModel model)
{
foreach (var x in model)
{
bool IsThisCheked= Convert.ToBoolean(collection[x.name].ToString());
}
}
I think you can pass the whole list of checkboxes to the post controller and then iterate through them like
[HttpPost]
public ActionResult About(List<Requirements> requirements)
{
foreach (var item in requirements)
{
if (item.IsSelected == true)
{
//perform some operation
}
}
List is the list that I passed from view to controller on submitting the form
Now coming to view it can be something like this
#for (int i = 0; i < Model.Requirements.Count; i++)
{
#Html.HiddenFor(m => m.Requirements[i].RId)
#Html.CheckBoxFor(m => m.Requirements[i].IsSelected, new { id = "requirements_" + i, #class = "divider" })
#Html.DisplayFor(m => m.Requirements[i].RName)
}
RId,RName,IsSelected(someproperty to store boolean) are my model properties related to checkboxlist
In a SelectItem, I get back a collection of objects/values for use in a dropdown list. I need to find a specific item in the returned list and set the Selected property to true if it matches a value (stateCode) that is passed in... I have this which, obviously, doesn't work. The line after the //psuedo comment is where I'd like to make the change. Any idea on how to do this? I don't seem to have access to the properties I want to change...
SelectList retVal = new SelectList(this.db.States.Where(x => x.Col1== someVal), "ValueCol", "TextCol", someVal);
foreach (SelectListItem item in retVal) {
//psuedo
retVal[item.Index].Selected = item.Value == stateCode ? true : false;
}
return retVal;
As requested, here is how I'm rendering the dropdown that this SelectItem is bound to:
<div class="select" id="StateDropDown">
<label for="StateProvince">#Resources.Expert.State_or_Province:</label>
#Html.DropDownListFor(x => x.StateProvince, Model.StateList)
</div>
To assign a selected value to the drop down you don't need to set the value in your select list. all you need to do is set the value on your model when using a for helper. So for your drop down
#Html.DropDownListFor(x => x.StateProvince, Model.StateList)
make sure that you set StateProvince to the value that you want to select. Also make sure that the value of StateProvince Matches a value that is in your SelectList Model.StateList.
It would be appropriate to pass selected value to #Html.DropdownList method.
Assuming stateCode is state you want to be selected.
Like this.
<div class="select" id="StateDropDown">
<label for="StateProvince">#Resources.Expert.State_or_Province:</label>
#Html.DropDownListFor(x => x.StateProvince, Model.StateList, stateCode)
My controller passes a list of objects to my view allowing me to:
#foreach (var optiongroup in Model)
{
Within the Model is an IEnumerable<Option>. I need to sort this list of options such that when I:
#foreach (var option in optiongroup.Options){
I end up with a list where items are sorted on the property called option.SortOrder instead of the ordinal position of each item.
So how do I get a list sorted prior to the foreach? I've tried:
#foreach (var option in optiongroup.Options.OrderByDescending(o => optiongroup.SortOrder))
and:
IEnumerable<Option> allOptions = optiongroup.Options.OrderByDescending(o => optiongroup.SortOrder);
// then foreaching the allOptions list
but have yet to achieve joy.
thx
This
IEnumerable<Option> allOptions = optiongroup.Options.OrderByDescending(o => optiongroup.SortOrder);
should be
IEnumerable<Option> allOptions = optiongroup.Options.OrderByDescending(o => o.SortOrder);
I have an ArrayList that contains some HashTables , and I have a ListView that contains some items.
What I need is to match the array list with the list items.
If an item in the list view and not in the array list, then it should be removed from the list view.
If not in either the list view or the array list, then add it to list view.
This is some code:
ArrayList online_list = users;
foreach (Hashtable i in online_list)
{
ListViewItem item = new ListViewItem();
item.Text = (string)i["u_name"];
item.Name = (string)i["id"];
item.ImageIndex = 0;
lstvUsers.Items.Add(item);
}
This code adds all array list items to the list view without the check!
You could first clear all items of the ListView, then add all in the ArrayList:
lstvUsers.Clear();
foreach (Hashtable i in online_list)
{
ListViewItem item = new ListViewItem();
item.Text = (string)i["u_name"];
item.Name = (string)i["id"];
item.ImageIndex = 0;
lstvUsers.Items.Add(item);
}
You should use ListView.Clear instead of ListView.Items.Clear: https://stackoverflow.com/a/10170049/284240
Edit: Since you're adamant that you only want to remove items from the ListView that are not in the ArrayList and add items that are not in the ListView but in the ArrayList . That approach is significantly less efficient since you need to compare each item in the ListView with each item in the ArrayList (and vice-versa) instead of comparing nothing.
For example:
var addItems = online_list
.Cast<Hashtable>()
.Where(ht => !lstvUsers.Items.ContainsKey((string)ht["id"]));
var removeItems = lstvUsers.Items
.Cast<ListViewItem>()
.Where(lvi => !online_list.Cast<Hashtable>().Any(ht => (string)ht["id"] ==lvi.Name));
foreach (var removeItem in removeItems)
{
lstvUsers.Items.Remove(removeItem);
}
foreach (var addHashTable in addItems)
{
ListViewItem item = new ListViewItem();
item.Text = (string)addHashTable["u_name"];
item.Name = (string)addHashTable["id"];
lstvUsers.Items.Add(item);
}