I have a Search Edit view which is strongly typed to my Search model class seen below (simplified).
I want to display the custodians that are attributed to the Search being edited in a listbox showing all Custodians, with the current ones selected.
My controller's Get Edit action is thus:
public ActionResult Edit(int id, int searchListId = 0)
{
if (searchListId != 0)
{
Session["CurrentSearchListID"] = searchListId;
}
ProjectContext mydb = db;
Search search = Search.Find(mydb, id);
IEnumerable<SelectListItem> selectedItems =
from c in Custodian.List(mydb)
select new SelectListItem
{
Selected = (search.Custodians.Contains(c)),
Text = c.CustodianName,
Value = c.ToString()
};
ViewBag.Custodians = selectedItems;
return View(search);
}
And my Views listbox is thus:
#{
//List<Kiersted.Keps.BusinessObjects.Custodian> Custodians = ViewBag.Custodians;
IEnumerable<SelectListItem> SelectedItems = ViewBag.Custodians;
}
#Html.ListBox("Custodians", SelectedItems);
This produces a listbox with the Custodians depicted, but none are selected (I have confirmed that several of the SelectListItems accurately describe the custodian as selected. I have tried using ListBoxFor and it produces the same thing when populated with a MultiSelectList.
Finally I decided to just force it to do what I want, but this does not return selected Custodians on Submit.
<select id="Custodians" multiple="multiple" name="Custodians">
#foreach (Kiersted.Keps.BusinessObjects.Custodian cust in Custodians)
{
if (Model.Custodians.Contains(cust))
{
<option value="#cust.CustodianID" selected="selected">#cust.CustodianName</option>
}
else
{
<option value="#cust.CustodianID" >#cust.CustodianName</option>
}
}
</select>
Anyone know how you are supposed to do this?
Edits:
ListBoxFor example
OK so after fiddling around with it for a while longer, I have now gotten Custodians selected in the listbox that correspond to the Search Custodians. Below is the view code:
<div class="editor-field">
#Html.ListBoxFor(model => model.Custodians, allCustodians.Select(cust => new SelectListItem {
Text = cust.CustodianName,
Value = cust.CustodianID.ToString(),
Selected = true}),
new { Multiple = "multiple" })
</div>
If I select several more custodians, how do I get them (or their corresponding values rather) back to the control upon submit?
Seeing that after your edit the problem boils down to multiple select model binding, perhaps you will find these useful?
How does a multiple select list work with model binding in ASP.NET MVC?
http://ittecture.wordpress.com/2009/04/30/tip-of-the-day-198-asp-net-mvc-listbox-controls/
Related
I'm still pretty new to .NET, but I think I've read everything there is to read on this subject (including similar questions on SO, which is where I got some of the things I've tried). I feel like I've tried everything possible and I still can't get it to work.
I have a Note class and a Category class. Pretty straightforward, each note has a Category property, so I want to have a dropdown list in my Create view that displays categories. I can get a list to display the category names correctly, but that's it. It keeps telling me there's no IEnumerable in my ViewData called "Categories" when there definitely, 1000% for sure is...
The Create action in my NoteController looks like this:
// GET: Create
public ActionResult Create()
{
SelectList items = (new CategoryService()).GetCategories().Select(c => new SelectListItem
{
Value = c.CategoryId.ToString(),
Text = c.Name
}) as SelectList;
ViewData["Categories"] = items;
return View();
}
And I've tried a few variations in the view:
#Html.DropDownListFor(e=>e.CategoryId , (IEnumerable<SelectListItem>) ViewData["Categories"])
#Html.DropDownList("Categories", "Select a Category")
My Create view uses a NoteCreate model, which has this:
public class NoteCreate {
...
[Display(Name = "Category")]
[Required]
public string CategoryId { get; set; }
And my NoteService has a CreateNote method like so:
public bool CreateNote(NoteCreate model)
{
using (var ctx = new ApplicationDbContext())
{
bool isValid = int.TryParse(model.CategoryId, out int id);
if (!isValid)
{
id = 0;
}
var entity =
new Note()
{
OwnerId = _userId,
Title = model.Title,
Content = model.Content,
CreatedUtc = DateTimeOffset.Now,
Status = model.Status,
CategoryId = id
};
ctx.Notes.Add(entity);
return ctx.SaveChanges() == 1;
}
}
I figured I have to turn the ID into a string for the sake of the dropdown list (because SelectListItem's Value and Text are strings), which is why I parse it back into an int here
I tried attaching the list to the ViewBag instead, and I've tried variations of both DropDownListFor and DropDownList
One of those combinations resulted in a dropdown list actually showing, and I don't remember what it was, but selecting an item resulted in a null being passed to the NoteCreate method (model.CategoryId)
Can anyone help me, and potentially many others who will struggle with this in the future because the documentation is so terrible?
UPDATE:
My controller has been refactored to:
// GET: Create
public ActionResult Create()
{
List<SelectListItem> li = new List<SelectListItem>();
List<Category> Categories = (new CategoryService()).GetCategories().ToList();
var query = from c in Categories
select new SelectListItem()
{
Value = c.CategoryId.ToString(),
Text = c.Name
};
li = query.ToList();
ViewBag.Categories = li;
return View();
}
and my view has been refactored to:
#Html.DropDownList("Categories", ViewBag.Categories as SelectList, new { #class = "form-control" })
This is closer, as I can now load the view and see the Category names in the dropdown. However, when I save, model.CategoryId in my CreateNote method is null, so the CategoryId value isn't actually being passed from the dropdown into the model.
If ViewModel is used in the view then its better to paa the data through model properties to the view. No need to put the collection for Dropdownlist in ViewData or ViewBag.
For the detail way of using Dropdownlist through SelectList and pass to the view through, I would refer an answer I had posted:
MVC C# Dropdown list Showing System.Web.SelectListItem on the model and can not blind to controller
The model passed to your view needs a property for CategoryId.
Your Html Helper is looking for CategoryId here:
#Html.DropDownListFor(e=>e.CategoryId
Ok... I figured it out.
It's so stupid.
The key you use to store the SelectList in your ViewData HAS to be the same as the name of the property on the model, even though you can explicitly tell it to use the list using a different key....
So even if you wanted to use the same SelectList for a few different properties (but process them differently in your service, say), you'd have to pass it to the ViewData redundantly for each property
So instead of passing my SelectList through as ViewBag.Categories, I passed it in as ViewBag.CategoryId, and that worked.
I'm going to go drink a lot of alcohol now.
In Controller
List<SelectListItem> li = new List<SelectListItem>();
var query = from of in your_context.Categories
select new SelectListItem()
{
Value = of.CategoryId.ToString(),
Text = of.Name
};
li = query.ToList();
ViewBag.Category_ = li;
View
<div class="col-md-10">
#Html.DropDownList("Categories", ViewBag.Category_ as List<SelectListItem>, new { #class = "form-control" })
</div>
I have a hard coded select list, pulling Value and Text from the db.
I have a specific item I want to set as the "default", so I order the list to specifically put it first in line ("Wip"). However, when the list is rendered in HTML, the order of the list is correct, but the selected value is the item with the smallest value, even though it is at the bottom of the list due to ordering descending.
Model:
public IEnumerable<SelectListItem> BinOptionsList { get; set; }
Data Access:
public IEnumerable<SelectListItem> PopulateBinList()
{
using (var db = new InventoryContext())
{
var data = db.StorageBin.OrderByDescending(s => s.BinCode == "Wip").ThenBy(s => s.BinCode).Select(s => new SelectListItem()
{
Text = s.BinCode,
Value = s.BinId.ToString()
}).ToList();
return data;
}
}
Controller:
model.BinOptionsList = dal.PopulateBinList()
View:
#Html.DropDownListFor(model => model.BinId, Model.BinOptionsList, new { #class = "form-control" })
The list renders in the View with "Wip" as the first selection, but the rendered "selected=selected" option is the item with id=0.
I know I can set the 'Selected' value in the Data Access method, but then I cant use this in an edit form that would already have a selected value.
Update - Rendered HTML:
<select class="form-control" data-val="true" data-val-number="The field Bin Code must be a number." data-val-required="The Bin Code field is required." id="BinId" name="BinId">
<option value="582">WIP</option>
<option value="595">0888</option>
<option selected="selected" value="0">0919</option>
<option value="1">1</option>
<option value="2">1A1</option>
<option value="3">1A10</option>
<option value="4">1A11</option>
</select>
I'm pretty sure BindId is equal to 0. If BindId is a simple Integer then it will always be equal to 0 by default. You'll need to set it to 582 yourself or set it as Integer? which would set the default as null.
So you may not prefer this answer but let me outline one quick thing. Your select list should not be of your model. The value selected from your select this should be part of your model. You are putting too much overhead into your model and it is having in impact on your view. Refactor it. Put your select list in your ViewBag for you to use in your view, stop passing it back and forth. This will keep your model compact and allow you to set your options properly.
Here is a simple example.
What would be your Data Access (just stubbing it out for example sake and yes setting it to static for example simplicity):
public static IEnumerable<SelectListItem> PopulateBinList()
{
return new List<SelectListItem>{ new SelectListItem {
Text = "WIP", Value = "582"
}, new SelectListItem {
Text = "0888", Value = "595"
} , new SelectListItem {
Text = "0", Value = "0919"
}, new SelectListItem {
Text = "1", Value = "1"
}};
}
Then your model (just adding the one property for example)
public class BinModel
{
public string BinId { get; set; }
}
In your controller
public ActionResult Index()
{
//load up your select list into the view bag
ViewBag.BinOptions = ViewHelper.PopulateBinList();
//preset the value of your desired object
var bm = new BinModel { BinId = "582" };
return View(bm);
}
The in your view you are going to bind to model property but use your temp list defined in the view bag to fill the options. Presetting your model's property will auto select which value is defaulted in the select list:
#Html.DropDownListFor(x => x.BinId, (IEnumerable<SelectListItem>)ViewBag.BinOptions, null, new { #class ="form-control" })
Please let me know if this does not make sense or needs to be expanded on.
I use JavaScript for populating a list called "groups".
Then I create a DropDownList:
<div class="form-group">
<div class="col-md-10">
#Html.DropDownList("groups", new SelectList(string.Empty, "Value", "Text"), "Choose...")
</div>
</div>
The DropDownList displays fine.
What I need to do is assign the chosen value from "groups" to the model.group_id.
I don't know how to get the item chosen in DropDownList in the controller method. Thank you for any advice.
If you need it to bind to group_id then use that as the name:
#Html.DropDownList("group_id", ...)
Or, even better, use the strongly-typed helper:
#Html.DropDownListFor(m => m.group_id, ...)
Assuming you have a form field in your form with the name group_id like this and you want to set the selected value from your dropdown to that field for some reason,
#Html.HiddenFor(s=>s.group_id)
<div class="form-group">
#Html.DropDownList("groups",new SelectList(string.Empty, "Value", "Text"), "Choose...")
</div>
You can listen to the change event of the dropdown and get the selected option value and set to the group_id
$(function(){
$("#groups").change(function(e){
var v=$(this).val();
$("#group_id").val(v);
});
});
I am not sure why you are loading the dropdown content via javascript, but there are other better ways to render a dropdown and pass the selected value back to your controller as explained in this post.
Add a SelectedGroup property to your view model
public class CreateSomethingViewModel
{
public int SelectedGroup {set;get;}
public List<SelectListItem> Groups {set;get;}
}
and in your GET action, If you want to load the Groups, you can do it
public ActionResult Create()
{
var vm = new CreateSomethingViewModel();
//Hard coded for demo. You may replace with your db entries (see below)
vm.Groups = new List<SelectListItem> {
new SelectListItem { Value="1","Chase bank" },
new SelectListItem { Value="2","PNCbank" },
new SelectListItem { Value="3","BOA" }
};
return View(vm);
}
And in your view
#model CreateSomethingViewModel
#using(Html.BeginForm())
{
#Html.DropDownListFor(s=>s.SelectedGroup,Model.Groups)
<input type="submi" />
}
With this you do not need to use any js code ( Even if you load the dropdown content via javascript), when user changes the dropdown option value, It will be set as the value of the SelectedGroup property.
[HttpPost]
public ActionResult Create(CreateSomethingViewModel model)
{
// check model.SelectedGroup
// to do : Save and return/redirect
}
I'm using Microsoft VS 2010 C#, MVC3.
I have Calsserooms and Students with many to many relation ship, so I add an intermediat table called Classroom_Students.
When adding students to a classroom, I use a combo box in my view filled with all students names, I choose one by one in every submit
#using (Html.BeginForm("AddStudentToClassroom", "Calssrooms", FormMethod.Post))
{
#Html.LabelFor(c=>c.Students, "Choose a Student")
<select name = "StudentID">
#foreach (var it in Model.Students)
{
<option value="#it.ID">#it.StudentName </option>
}
</select>
<input type="submit" value= "Add" />
}
My question is:
How can I use gride, instead of this combo, to select many students, select all or deselect all to add???
I'll appreciate any help.
This is the code in my controller.
For page first call, I fill combobox as following:
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult AddStudentToClassroom(int id) //id of calssroom
{
using (ExaminationEntities en = new ExaminationEntities())
{
ClassroomDetails ClsromView = new ClassroomDetails (); // these are for
ClsromView.Classroom = en.Classroom.Single(c => c.ID == id);// loading calssroom information and to
ClsromView.Students = en.Students.ToList(); // fill students list for the combobox
return View(ClsromView);
}
}
When submiting the form, view, and click the add button, it calls the following overloaded add function for saving data:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddStudentToClassroom(AddStudToCals ClasStud) //ClasStud is the submited data from the view
{
using (ExaminationEntities en = new ExaminationEntities())
{
ClassroomDetails ClsromView = new ClassroomDetails(); // these are for
ClsromView.Calssroom = en.Calssroom.Single(c => c.ID == ClasStud.ClassroomID); // loading calssroom information and to
ClsromView.Students = en.Student.ToList(); // fill students list for the combobox
using (ExaminationEntities exn = new ExaminationEntities())
{
Calssroom_Student To_DB_ClasStud = new Calssroom_Student (); //To_DB_ClasStud object to get the submited values and to save it in the DB
To_DB_ClasStud.CalssroomID = ClasStud.CalssroomID;
To_DB_ClasStud.StudentID = ClasStud.StdentID;
en.AddToClassroom_Student(To_DB_ClasStud);
en.SaveChanges();
}
return View(ClsromView);
}
}
Well, the option that requires the least changes to your markup is to add the multiple property to your select. Then, change the action method to accept a params int[] ids, iterate through them, and you should be good-to-go. At worst, you might have to change your parameter to a string and do a Split() on ,, but I don't recall that being how the model binder supports multi-selects.
If this doesn't seem to fit your needs, there is an article on the ASP.NET website that explains using a MultiSelectList to bind to the ListBox helper, here:
http://www.asp.net/mvc/tutorials/javascript/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc
I'm creating a question/answer page that contains multiple object types (radio button, dropdown, check boxes).
Id QuestionText AnswerId AnswerText ObjectType
1 text one 1 Personal DropDown
1 text two 2 Business DropDown
2 Text three 3 Direct Deposit CheckBox
2 text four 4 Some Answer CheckBox
I have a model that contains a list of all questions, answers, and object types.
How can I populate (as an example) the dropdownlistfor with only two items out of the list, then populate a group of related checkboxes, then populate a group of related radio buttons?
The dropdownlistfor looks to enumerate on a model.
My code which doesn't work:
#if (Model != null)
{
for (int i = 0; i < Model.Count; i++)
{
if (Model[i].AdditionalQuestionTypeId == 1)
{
#Html.DropDownListFor(model => model[i].AdditionalQuestionId, ((IEnumerable<Curo.Web.InterAcct.Models.AdditionalQuestionAnswerModel>)Model[i].AnswerText)
.Select(option => new SelectListItem
{
Text = (option == null ? "None" : option.Description),
Value = option.Id.ToString(),
Selected = (Model != null) && (option.Id == Model[i].AdditionalQuestionId)
}), "Choose...")
It's not the best idea to clog up your view with a bunch of logic. That is actually not the desired approach of MVC.
Use this logic in your controller and not the View.
Create you options in the controller that you want for the desired scenario and set the options to the property on the Model. Then your view will simply bind to that property.
public class MyModel {
public string MyValue { get; set;}
public List<SelectListItem> Options { get; set; }
}
public ActionResult MyAction(){
MyModel model = new MyModel();
// populate options here
model.Options = new List<SelectListItem>();
return View(model);
}
Then your view:
#Html.DropDownListFor(m => m.MyValue, m => m.Options)
It's hard to tell from your code, but I think you are almost there. You need to do the dropdownlistfor statement with an IEnumerable, but your syntax appears to be off:
#Html.DropDownListFor(model => model[i].AdditionalQuestionId, new SelectList(Model.Answers.Where(f=>**Some code to select what values you want**), "Id", "Description", Model[i].AdditionalQuestionId))
It would help to see an error message, but I think it is just syntax at this point.