Html.Dropdonlist and selected value - asp.net-mvc

I have the following code:
int StatusID = ViewBag.DefaultStatus.StatusID;
List<NEOGOV_Ideas.Models.Status> statusList = ViewBag.StatusList;
#Html.DropDownList("DefaultStatus", new SelectList(statusList, "StatusID", "StatusName", StatusID))
but selected value does not set. Why?

Try like this in your controller action:
// set to a value that you want to be preselected
ViewBag.DefaultStatus = 123;
ViewBag.StatusList = ...
and in the view:
#{ List<NEOGOV_Ideas.Models.Status> statusList = ViewBag.StatusList; }
#Html.DropDownList(
"DefaultStatus",
new SelectList(statusList, "StatusID", "StatusName")
)
But I would recommend you using view models:
public class MyViewModel
{
public int SelectedStatusID { get; set; }
public SelectList Statuses { get; set; }
}
then in your controller action populate this view model and pass it to the view:
public ActionResult Foo()
{
List<NEOGOV_Ideas.Models.Status> statusList = ...
var model = new MyViewModel
{
// set to a value that you want to be preselected
SelectedStatusID = 123,
Statuses = new SelectList(statusList, "StatusID", "StatusName")
};
return View(model);
}
and finally in your strongly typed view:
#model MyViewModel
#Html.DropDownListFor(x => x.SelectedStatusID, Model.Statuses)

Related

I want to show selected value of dropdown list

Selected value is not coming when I am trying to check, drop down list is showing all the names, but when I am trying to show the selected value of the dropdownlist in the controller, option is not coming.
Controller:
public ActionResult Index1()
{
Class1 cs1 = new Class1();
return View(cs1);
}
[HttpPost]
public ActionResult Index1(Class1 cs)
{
var selecteditem = cs.psudetail.Find(p => p.Section_PSU == cs.psudetail.ToString());
if (selecteditem != null)
{
}
}
Model class:
namespace WebApplication1.Models
{
public class Class1
{
public List<PSUMaster> psudetail
{
get
{
PSUEntities pe = new PSUEntities();
return pe.PSUMasters.ToList();
}
}
}
}
And the View with Model:
#model WebApplication1.Models.Class1
#{
ViewBag.Title = "Index1";
}
<br />
#Html.DropDownListFor(m => m.psudetail, new SelectList(Model.psudetail, "S_no", "Section_PSU"), "--Select PSU--")
You need to have a property that can "store" the selection you make in the list. Extend the view model (Class1) to include a property SelectedPSU. I guess that S_no in the PSUMaster is the ID, and of type integer. Otherwise adjust the code accordingly!
I have also changed the list to be just a list, and then the controller can worry about populating it. This pattern fits MVC better (keep the model simple).
Updated class:
namespace WebApplication1.Models
{
public class PsuViewModel
{
public int SelectedPSU { get; set; }
public List<PSUMaster> PSU { get; set; }
}
}
Next, the controller has to be updated to pass the list to the view model in the GET Index method:
public ActionResult Index1()
{
var pe = new PSUEntities();
return View(new PsuViewModel {
PSU = pe.PSUMasters.ToList()
});
}
Now we can use the SelectedPSU property in our view:
#model WebApplication1.Models.Class1
#{
ViewBag.Title = "Index1";
}
<br />
#Html.DropDownListFor(m => m.SelectedPSU, new SelectList(Model.PSU, "S_no", "Section_PSU"), "--Select PSU--")
...and we can get the ID in the controller:
[HttpPost]
public ActionResult Index1(PsuViewModel model)
{
var pe = new PSUEntities();
var selectedPsu = pe.PSUMasters.FirstOrDefault(p => p.S_no == model.SelectedPSU);
if (selectedPsu != null) {
// ...
}
}

Getting Selected Values from Multiple Dropdowns in MVC web application

I am trying to build a web application having multiple drop downs. I have used enums in my model to populate these drop down and there is a single from submit button in my view. I am trying to figure out how could I get all the selected Index from these drop down with 1 button click.
My Controller looks something like this:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new DropDownModel();
return View(model);
}
[HttpPost]
public ActionResult Index(DropDownModel model)
{
// Get the selected value
int id = model.SelectedId;
return View();
}
public ActionResult About()
{
return View();
}
}
DropDown in my view:
#Html.DropDownListFor(x => x.SelectedId, Enum.GetNames(typeof(BTSWeb.Models.BillTemplate)).Select(e => new SelectListItem { Text = e }),"--BillTemplate--",new { style = "width:108px;font-size:90%;border-radius: 6.5px 6.5px 6.5px 6.5px" })
<span style="margin-left:1px"></span>
#Html.DropDownListFor(x => x.SelectedId, Enum.GetNames(typeof(BTSWeb.Models.ReadType)).Select(e => new SelectListItem { Text = e }),"--Read Type--",new { style = "width:70px;font-size:90%;border-radius: 6.5px 6.5px 6.5px 6.5px" })
<input type="submit" value="Submit" hidden="hidden"/>
and My Model:
namespace BTSWeb.Models
{
public enum States { ANY, FL, TX, GA, NE };
public enum PaymentType { ANY, Email, Paper, No };
public class DropDownModel
{
public int SelectedId { get; set; }
}
}
The problem is you are using DropDownModel as your view model. You will only ever be able to populate on selectedID using this. What you need to do is somehting like
public class ViewModel
{
public int SelectedStateId { get; set; }
public int SelecPaymentTypeId { get; set; }
}
then in your controller you would pass in
var viewModel = new ViewModel()
return View(ViewModel);
and on your view you would have
#Html.DropDownListFor(x => x.SelectedStateId, Enum.GetNames(typeof(BTSWeb.Models.BillTemplate)).Select(e => new SelectListItem { Text = e }),"--BillTemplate--",new { style = "width:108px;font-size:90%;border-radius: 6.5px 6.5px 6.5px 6.5px" })
<span style="margin-left:1px"></span>
#Html.DropDownListFor(x => x.SelecPaymentTypeId , Enum.GetNames(typeof(BTSWeb.Models.ReadType)).Select(e => new SelectListItem { Text = e }),"--Read Type--",new { style = "width:70px;font-size:90%;border-radius: 6.5px 6.5px 6.5px 6.5px" })
and finally on your controller post method you would have
[HttpPost]
public ActionResult Index(ViewModelmodel)
{
// Get the selected value
int id = model.SelectedStateId;
int id2 = model.SelecPaymentTypeId;
return View();
}

DropDownListFor - why selected element is always the first?

I have a DropDownListFor in my View:
#model UserProfileViewModel
#Html.DropDownListFor(x => x.PreferredLangID,
new SelectList(Model.PreferredLanguages,
"LanguageID",
"DisplayName",
Model.PreferredLang))
Controller action:
public ActionResult EditProfile()
{
List<Language> languages = Code.LanguageLogic.GetAllLanguages();
UserProfile profile = Code.ProfileLogic.GetUserProfile();
var viewModel = new UserProfileViewModel
{
UserID = profile.UserID,
PreferredLanguages = languages,
PreferredLang = profile.PreferredLang
};
return View(viewModel);
}
I thought, that if I gave Model.PreferredLang as 4th paramater in SelectList's contructor, that element will be selected in dropdown, when page loads. But selected element is always the first one in list.
The Model:
public class UserProfileViewModel
{
public Guid UserID { get; set; }
public Language PreferredLang { get; set; }
public int PreferredLangID { get; set; }
public IEnumerable<Language> PreferredLanguages { get; set; }
//...
}
I don't know the details of the type, so I can't say for sure, but I'm guessing you might need:
#Html.DropDownListFor(x => x.PreferredLangID,
new SelectList(Model.PreferredLanguages,
"LanguageID",
"DisplayName",
Model.PreferredLang.PreferredLangId))
ETA:
Or, with your addition:
#Html.DropDownListFor(x => x.PreferredLangID,
new SelectList(Model.PreferredLanguages,
"LanguageID",
"DisplayName",
Model.PreferredLangId))
The second snipped for View was correct:
#Html.DropDownListFor(x => x.PreferredLangID,
new SelectList(Model.PreferredLanguages,
"LanguageID",
"DisplayName",
Model.PreferredLangId))
But the Controller was also missing something. Model.PreferredLangID must be also set:
var viewModel = new UserProfileViewModel
{
UserID = profile.UserID,
IsAdministrator = profile.IsAdministrator,
PreferredLanguages = languages,
PreferredLangID = profile.PreferredLang.LanguageID
};
I'm not sure, why this didn't work with
new SelectList(Model.PreferredLanguages,
"LanguageID",
"DisplayName",
Model.PreferredLang.LanguageID))

MVC DropDownList SelectedValue not displaying correctly

I tried searching and didn't find anything that fixed my problem. I have a DropDownList on a Razor view that will not show the the item that I have marked as Selected in the SelectList. Here is the controller code that populates the list:
var statuses = new SelectList(db.OrderStatuses, "ID", "Name", order.Status.ID.ToString());
ViewBag.Statuses = statuses;
return View(vm);
Here is the View code:
<div class="display-label">
Order Status</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.StatusID, (SelectList)ViewBag.Statuses)
#Html.ValidationMessageFor(model => model.StatusID)
</div>
I walk through it and even in the view it has the correct SelectedValue however the DDL always shows the first item in the list regardless of the selected value. Can anyone point out what I am doing wrong to get the DDL to default to the SelectValue?
The last argument of the SelectList constructor (in which you hope to be able to pass the selected value id) is ignored because the DropDownListFor helper uses the lambda expression you passed as first argument and uses the value of the specific property.
So here's the ugly way to do that:
Model:
public class MyModel
{
public int StatusID { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
// TODO: obviously this comes from your DB,
// but I hate showing code on SO that people are
// not able to compile and play with because it has
// gazzilion of external dependencies
var statuses = new SelectList(
new[]
{
new { ID = 1, Name = "status 1" },
new { ID = 2, Name = "status 2" },
new { ID = 3, Name = "status 3" },
new { ID = 4, Name = "status 4" },
},
"ID",
"Name"
);
ViewBag.Statuses = statuses;
var model = new MyModel();
model.StatusID = 3; // preselect the element with ID=3 in the list
return View(model);
}
}
View:
#model MyModel
...
#Html.DropDownListFor(model => model.StatusID, (SelectList)ViewBag.Statuses)
and here's the correct way, using real view model:
Model
public class MyModel
{
public int StatusID { get; set; }
public IEnumerable<SelectListItem> Statuses { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
// TODO: obviously this comes from your DB,
// but I hate showing code on SO that people are
// not able to compile and play with because it has
// gazzilion of external dependencies
var statuses = new SelectList(
new[]
{
new { ID = 1, Name = "status 1" },
new { ID = 2, Name = "status 2" },
new { ID = 3, Name = "status 3" },
new { ID = 4, Name = "status 4" },
},
"ID",
"Name"
);
var model = new MyModel();
model.Statuses = statuses;
model.StatusID = 3; // preselect the element with ID=3 in the list
return View(model);
}
}
View:
#model MyModel
...
#Html.DropDownListFor(model => model.StatusID, Model.Statuses)
Make Sure that your return Selection Value is a String and not and int when you declare it in your model.
Example:
public class MyModel
{
public string StatusID { get; set; }
}
Create a view model for each view. Doing it this way you will only include what is needed on the screen. As I don't know where you are using this code, let us assume that you have a Create view to add a new order.
Create a new view model for your Create view:
public class OrderCreateViewModel
{
// Include other properties if needed, these are just for demo purposes
// This is the unique identifier of your order status,
// i.e. foreign key in your order table
public int OrderStatusId { get; set; }
// This is a list of all your order statuses populated from your order status table
public IEnumerable<OrderStatus> OrderStatuses { get; set; }
}
Order status class:
public class OrderStatus
{
public int Id { get; set; }
public string Name { get; set; }
}
In your Create view you would have the following:
#model MyProject.ViewModels.OrderCreateViewModel
#using (Html.BeginForm())
{
<table>
<tr>
<td><b>Order Status:</b></td>
<td>
#Html.DropDownListFor(x => x.OrderStatusId,
new SelectList(Model.OrderStatuses, "Id", "Name", Model.OrderStatusId),
"-- Select --"
)
#Html.ValidationMessageFor(x => x.OrderStatusId)
</td>
</tr>
</table>
<!-- Add other HTML controls if required and your submit button -->
}
Your Create action methods:
public ActionResult Create()
{
OrderCreateViewModel viewModel = new OrderCreateViewModel
{
// Here you do database call to populate your dropdown
OrderStatuses = orderStatusService.GetAllOrderStatuses()
};
return View(viewModel);
}
[HttpPost]
public ActionResult Create(OrderCreateViewModel viewModel)
{
// Check that viewModel is not null
if (!ModelState.IsValid)
{
viewModel.OrderStatuses = orderStatusService.GetAllOrderStatuses();
return View(viewModel);
}
// Mapping
// Insert order into database
// Return the view where you need to be
}
This will persist your selections when you click the submit button and is redirected back to the create view for error handling.
I hope this helps.
For me, the issue was caused by big css padding numbers ( top & bottom padding inside the dropdown field). Basically, the item was being shown but not visible because it was way down. I FIXED it by making my padding numbers smaller.
I leave this in case it helps someone else. I had a very similar problem and none of the answers helped.
I had a property in my ViewData with the same name as the selector for the lambda expression, basically as if you would've had ViewData["StatusId"] set to something.
After I changed the name of the anonymous property in the ViewData the DropDownList helper worked as expected.
Weird though.
My solution was this...
Where the current selected item is the ProjectManagerID.
View:
#Html.DropDownList("ProjectManagerID", Model.DropDownListProjectManager, new { #class = "form-control" })
Model:
public class ClsDropDownCollection
{
public List<SelectListItem> DropDownListProjectManager { get; set; }
public Guid ProjectManagerID { get; set; }
}
Generate dropdown:
public List<SelectListItem> ProjectManagerDropdown()
{
List<SelectListItem> dropDown = new List<SelectListItem>();
SelectListItem listItem = new SelectListItem();
List<ClsProjectManager> tempList = bc.GetAllProductManagers();
foreach (ClsProjectManager item in tempList)
{
listItem = new SelectListItem();
listItem.Text = item.ProjectManagerName;
listItem.Value = item.ProjectManagerID.ToString();
dropDown.Add(listItem);
}
return dropDown;
}
Please find sample code below.
public class Temp
{
public int id { get; set; }
public string valueString { get; set; }
}
Controller
public ActionResult Index()
{
// Assuming here that you have written a method which will return the list of Temp objects.
List<Temp> temps = GetList();
var tempData = new SelectList(temps, "id", "valueString",3);
ViewBag.Statuses = tempData;
return View();
}
View
#Html.DropDownListFor(model => model.id, (SelectList)ViewBag.Statuses)
#Html.ValidationMessageFor(model => model.id)

MVC3 SelectedValue

In my model:
public SelectList QuestionGroupSelectList { get; set; }
------
List<QuestionGroup> questionGroupList = questionGroupRepository.GetQuestionGroup_BySurveyId(survey.Id);
Dictionary<int, string> questionGroupDictionary = questionGroupList.ToDictionary(l => l.Id, l => l.Name);
QuestionGroupSelectList = new SelectList(questionGroupDictionary, "key", "value", questionGroupId);
---------------------------------------
In view:
#Html.DropDownList("QuestionGroupSelectList", Model.QuestionGroupSelectList, "Choose Here")
When i debug i get 2 items in QuestionGroupSelectList (one with Id 30 and one with Id 35), and it says that the selectedValue is 35 (questionGroupId = 35)
But the selectedvalue does not work in the view, any ideas?
Thanks in advance!
You should use a different property to bind your dropdownlist value to. Also you should use view models and strongly typed helpers, like this:
public class MyViewModel
{
public int QuestionGroupId { get; set; }
public SelectList QuestionGroupSelectList { get; set; }
}
then you could have a controller action which populates this view model and passes it to the view:
public ActionResult Foo()
{
// This collection could come from anywhere
// normally you will query a repository here to fetch those values
var values = new[]
{
new { Key = "1", Value = "item 1" },
new { Key = "2", Value = "item 2" },
new { Key = "3", Value = "item 3" },
}
var model = new MyViewModel
{
// preselect the second value
QuestionGroupId = 2,
QuestionGroupSelectList = new SelectList(values, "Key", "Value")
}
return View(model);
}
and finally in your view:
#model MyViewModel
#Html.DropDownListFor(
x => x.QuestionGroupId,
Model.QuestionGroupSelectList,
"Choose Here"
)

Resources