I'm passing in a list of statuses into an Html.DropDownList. I've been searching for a way to choose one of those items as the default, so if the user doesn't change anything, the correct status is passed back to the model. Everything I've found deals with adding an additional value (usually a "null" option) to the list.
How do I default to an already existing item?
Model:
public class ListStatus
{
public string Name { get; set; }
public Guid StatusID { get; set; }
}
public class ViewModel
{
public List<ListStatus> Statuses { get; set; }
}
View:
#Html.DropDownList("StatusID", Model.Statuses.Select(s => new SelectListItem() { Text = s.Name, Value = s.StatusID.ToString() }), new { #class = "medium", required = true })
Sample Data:
'11111111-1111-1111-1111-111111111111': Option 1,
'22222222-2222-2222-2222-222222222222': Default,
'33333333-3333-3333-3333-333333333333': Option 3,
'44444444-4444-4444-4444-444444444444': Option 4
You can add another field to your ViewModel say SelectedStatus and set its value to your desired default. Then you can use #Html.DropDownListFor to display default value.
public class ViewModel
{
public Guid SelectedStatus {get;set;}
public List<ListStatus> Statuses { get; set; }
}
In your controller
[HttpGet]
public ActionResult Index()
{
List<ListStatus> lstStatus = new List<ListStatus>(){
new ListStatus() { Name="X",StatusID = Guid.NewGuid() },
new ListStatus() { Name="Y",StatusID = Guid.NewGuid() },
new ListStatus() { Name="Z",StatusID = Guid.NewGuid() }
};
ViewModel objModel = new ViewModel();
objModel.Statuses = lstStatus;
objModel.SelectedStatus = lstStatus[1].StatusID; // Select whatever you want here to be default.
return View(objModel);
}
In your view
#Html.DropDownListFor(m=>m.SelectedStatus, Model.Statuses.Select(s => new SelectListItem() { Text = s.Name, Value = s.StatusID.ToString() }), new { #class = "medium", required = true })
Here is fiddle : https://dotnetfiddle.net/vTJhaj
If you build a List<SelectListItem> in your controller and pass it back on the view model, you can easily find the one you want selected by default by using the Selected property.
https://msdn.microsoft.com/en-us/library/system.web.mvc.selectlistitem(v=vs.118).aspx
public class ViewModel
{
public List<SelectListItem> Statuses { get; set; }
}
// in controller
ViewModel model = new ViewModel();
// assumes listStatuses is still your ListStatus type.
model.Statuses = listStatuses.Select(s => new SelectListItem() {
Text = s.Name,
Value = s.StatusID.ToString(),
// or whatever your criteria may be.
Selected = s.Name == "22222222-2222-2222-2222-222222222222"
})
Now you don't need to convert to new types in the view, either.
Related
I have the following two models, one of which contains a list of the other model i.e. UserModels.
public class UserModel
{
public int SelectedUserId { get; set; }
public SelectList UserOptions { get; set; }
public UserModel()
{
var users = new List<SelectListItem>
{
new SelectListItem { Text = "Mickey Mouse", Value = "1" },
new SelectListItem { Text = "Goofy", Value = "2" },
new SelectListItem { Text = "Donald Duck", Value = "3" },
};
UserOptions = new SelectList(users, "Value", "Text");
}
}
public class MyModel
{
public IList<UserModel> Users { get; set; }
public MyModel()
{
Users = new List<UserModel>();
}
}
When I attempt to bind this list of UserModels to a MVC Razor page with multiple DropDownList, the values do not bind and the selected item in the DropDownList is not displayed correctly.
#for(int i=0; i < Model.Users.Count; i++)
{
#Html.DropDownListFor(x => x.Users[i].SelectedUserId, Model.Users[i].UserOptions)
}
However, if I select different values in each DropDownList on the page and then post the form back to the server, the correct values bind within each individual UserModel in the List of models i.e. 'Users'.
Am I missing something here? Is this a known bug? Why is it when setting the values of SelectedUserId in each model on the server, does the correct option in the select list not bind, but selecting an option in the select list on the web page does work?
#Html.DropDownListFor works very weird way, when you init one, you have to init selected value too. So if you create list like this:
Users.Add(new UserModel { SelectedUserId = "2" });
you will have to assign selected item inside of UserModel :
List<SelectListItem> users=null;
public string SelectedUserId
{
get { return users.Where(u=>u.Selected).FirstOrDefault().Value; }
set {
var sUser=users.Where(u=>u.Value=value).FirstOrDefault();
sUser.Selected=true;
}
}
if you use net core much better to use " select " tag. It assigns automatically.
The DropDownListFor is not selecting the SelectListItem that I am specifying should be selected. Unable to figure out why as all parameters appear to be correct.
ViewModel:
public class SchemesViewModel
{
public int SchemeId { get; set; }
public SelectList Schemes { get; set; }
}
Controller (select list preparation):
var schemes = schemeManager.GetUserSchemes(this.UserId);
var selectListItems = schemes.Select(x => new SelectListItem() { Value = x.Id.ToString(), Text = x.Name, Selected = (x.Id == 2) });
var vm = new UserSchemesViewModel()
{
Schemes = new SelectList(selectListItems, "Value", "Text", selectedValue: selectListItems.FirstOrDefault(x => x.Selected == true).Value)
};
return PartialView("_UserSchemes", vm);
View:
Note: This is where the select option with value of 2 is not selected!
#Html.DropDownListFor(x => x.SchemeId, Model.Schemes)
Setting the Selected property of SelectListItem is ignored by the DropDownListFor() method. Internally the method build a new IEnumerable<SelectListItem> using the Value of Text properties of you existing SelectList and sets the new Selected property based on the value of property you binding to. You need to set the value of SchemeId before you pass the model to the view.
There is also no point creating a second identical SelectList from you first one (its just unnecessary extra overhead).
Modify your code to
public class SchemesViewModel
{
public int SchemeId { get; set; }
public IEnumerable<SelectListItem> Schemes { get; set; }
}
Controller
var schemes = schemeManager.GetUserSchemes(this.UserId);
var selectListItems = schemes.Select(x => new SelectListItem()
{
Value = x.Id.ToString(),
Text = x.Name
});
var vm = new UserSchemesViewModel()
{
Schemes = selectListItems,
SchemeId = 2
};
return PartialView("_UserSchemes", vm);
Now if one of your options has value="2" then that option will be selected when you first render the view.
Model
public class Company
{
public int ID { get; set; }
....
public int WorkZoneID { get; set; }
public IEnumerable<SelectListItem> WorkZones { get; set; }
Controller:
ViewBag.Workzones = cmpRep.GetWorkzoneDrop();
Repository:
public List<SelectListItem> GetWorkzoneDrop()
{
SqlDataReader DR;
DR = Ado.ExecDataReaderProc("WorkZoneSelectActive");
List<SelectListItem> selectWorkZoneListItems = new List<SelectListItem>();
CompanyVMList C = new CompanyVMList();
C.Companies = new List<Company>();
while (DR.Read())
{
SelectListItem selectListItem = new SelectListItem
{
Text = Convert.ToString(DR["Name"]),
Value = Convert.ToString(DR["ID"]),
};
selectWorkZoneListItems.Add(selectListItem);
}
return selectWorkZoneListItems;
}
View
#Html.DropDownList("Workzones")
I want to assign selected dropdownlist value to int work zone int the mode how do i select value from dropdownlist to model or to controller
You need to bind your dropdownlist to property WorkZoneID
#Html.DropDownListFor(m => m.WorkZoneID, Model.Workzones)
and if your wanting to preselect an option, you need to set the value in the controller before you pass the model to the view. And since your model contains a property for the SelectList, then use it (don't use ViewBag)
Company model = new Company
{
WorkZoneID = 1 // set to a value that matches one of your options
Workzones = cmpRep.GetWorkzoneDrop();
};
return View(model);
and when you submit to
[HttpPost]
public ActionResult Edit(Company model)
the value of model.WorkZoneID will contain the value of the selected option.
I am trying to bind my model to Multiple Select in .net MVC. This is my model
public class RuoloProgetto
{
[Key]
public int id_ruolo_prog { get; set; }
[Display(Name = "Ruolo")]
public int id_ruolo { get; set; }
[ForeignKey("id_ruolo")]
public virtual Ruolo ruolo { get; set; }
public int id_progetto { get; set; }
//[ForeignKey("id_progetto")]
//public virtual Progetto progetto { get; set; }
[Display(Name = "Utente")]
public string id_utente { get; set; }
[ForeignKey("id_utente")]
public virtual IdentityUser utente { get; set; }
[DisplayName("Carico di lavoro in %")]
[Required]
public int percentuale { get; set; }
public int versione { get; set; }
[DisplayName("Moduli Responsabile")]
public int[] Choices { get; set; }
public virtual List<ModelRP> moduli { get; set; }
}
This is in my controller function that sets the values for the selectlist:
List<SelectListItem> specifiche = new List<SelectListItem>();
var specifiche2 = db.Specificha.Where(p => p.id_progetto == Progetti.id_progetto).Select(x => new { x.id_specifiche, x.desc_specifiche }).ToList();
foreach (var item in specifiche2)
{
specifiche.Add(new SelectListItem { Value = item.id_specifiche.ToString(), Text = item.desc_specifiche });
}
ViewData["Specs"] = specifiche;
and this is in my view:
#Html.ListBoxFor(m => item.Choices,
new MultiSelectList((IEnumerable<SelectListItem>)ViewData["Specs"], "Value", "Text",
item.moduli.Select(fl => new SelectListItem
{
Text = fl.moduloutente.desc_specifiche.ToString(),
Value = fl.moduloutente.id_specifiche.ToString(),
Selected = item.moduli.Any(y => y.id_specifiche == fl.id_specifiche)
})),
new
{
Selected = true,
#Class = "js-example-basic-multiple form-control",
Multiple = "multiple",
#Name = "progetto.ruoloprogetto[" + index + "].Choices",
#Id = "progetto.ruoloprogetto[" + index + "]_Choices",
#Placeholder = "Moduli",
})
The ViewData comes ok! The problem is with the selected values! When I check in immediate window item.moduli is correctly filled with the data, but nothing appears as selected in the interface!
Can someone see what I'm doing wrong?
Your binding the list box to property Choices so you need to set the value of Choices in the controller before you pass the view and then just
#Html.ListBoxFor(m => item.Choices, (IEnumerable<SelectListItem>)ViewData["Specs"], new { #class = "js-example-basic-multiple form-control" })
If the values of the option values are (say) 1 to 10, and Choices is [2, 4] then the second and forth options will be selected.
Note also do not need to set Multiple = "multiple" (thats already done by the helper), and you should not be trying to override the name attribute (other wise binding will fail on post back). In addition Selected and Placeholder are not valid attributes for <select>
Asp.net MVC 4
Entity Framework 5
LINQ
C#
I have a ViewModel I am using already. I am now adding my PermissionType model to my ViewModel.
This model represents a table in the database with the same name.
How do I turn this table into a #Html.DropDownListFor()
From the table for the 'text' I need 'name' from the database.
From the table for the 'value' I need 'ID' from the database.
How do I turn that model into a usable drop down list from my controller to my page?
ForumBoard model = new ForumBoard();
model.TPGForumQuery = db.TPGForums;
model.ProPit_User = db.ProPit_User.Where(m => m.username == userName).FirstOrDefault();
model.TPGForumTopicQuery = db.TPGForumTopics;
// need help here
model.PermissionType = // a list of all of the permission in this table
Edit:
public class ForumBoard
{
public ForumBoard()
{
this.ProPit_User = new ProPit_User();
this.TPGForum = new TPGForum();
this.PermissionType = new List<ListItem>();
}
List<ListItem> PermissionType { get; set; }
public virtual IEnumerable<TPGForum> TPGForumQuery { get; set; }
public virtual ProPit_User ProPit_User { get; set; }
public virtual IEnumerable<TPGForumTopic> TPGForumTopicQuery { get; set; }
public virtual TPGForum TPGForum { get; set; }
}
First, Change your view model
class ForumBoard
{
...
public IEnumerable<ListItem> PermissionType {get; set;}
...
}
Then, assign
ForumBoard model = new ForumBoard();
...
model.PermissionType = db.PermissionType
.Select(p=>
new ListItem (){ Text = p.FieldForText,
Value= p.FieldForValue });
Edit: If your fields are non string type, unfortunately, you have to first call ToList() method.
model.PermissionType = db.PermissionType
//.Select(p => new {Text = p.TextField, Value = p.permissionID })
.ToList()
.Select(p=> new ListItem (){
Text = p.Text.ToString(),
Value= p.Value.ToString()});
You can try this method :
//Controller :
using(MyContext context = new MyContext() )
{
IEnumerable<SelectListItem> listItems = context.PermissionType.Select( p => new SelectListItem{ Text = p.FieldNameFor , Value = p.FieldNameFor });
ViewBag.myList = listItems;
}
/*
Do other stuffs here and then return to View()
*/
// In your view :
#{
IIEnumerable<SelectListItem> listItems = (IEnumerable<SelectListItem>)ViewBag.myList;
}
#Html.DropDownListFor("Name of DropDownList" , listItems )