How to use DropDownList(ComboList) in MVC - c#

I want to use ComboBox in my MVC application but the Html.DropDownListFor is not giving the desired output. My controller code is as follows
public class Data_TableController : Controller
{
public ActionResult ListIndex()
{
List<SelectListItem> listSelectListItems = new List<SelectListItem>();
SelectListItem selectList = new SelectListItem()
{
Text = "DD",
Value = "1"
};
listSelectListItems.Add(selectList);
selectList = new SelectListItem()
{
Text = "XX",
Value = "2"
};
listSelectListItems.Add(selectList);
CitiesViewModel citiesViewModel = new CitiesViewModel()
{
Cities = listSelectListItems
};
return View(citiesViewModel);
}
}
ListIndex.cshtml code is:
#model MvcDemo.Models.CitiesViewModel
#{
ViewBag.Title = "ListIndex";
}
<div style=”font-family:Arial”>
<h2>Index</h2>
#using (Html.BeginForm())
{
#Html.DropDownListFor(m => m.SelectedCities, Model.Cities, new { size = Model.Cities.Count() })
<br />
<input type="submit" value=”Submit” />
}
</div>
View Model as follows
public class CitiesViewModel
{
public IEnumerable<string> SelectedCities { get; set; }
public IEnumerable<SelectListItem> Cities { get; set; }
}
But the HTML out is as pure list box. Also I like to know, How to add a label here? Attaching the output which I want to be in a combobox.

You are growing the 'display size' of your drop down list by adding:
new { size = Model.Cities.Count() }
So removing it will make it the default 'display size' of one element.
To add a label, I find the best way is as follows:
In your model, on the property use the DisplayName attribute:
[DisplayName("The City:")]
public string Cities { get; set; }
Then in your View display it like so:
#Html.LabelFor(m => m.Cities)
To give the drop down list / combobox a style do something like the following, i.e. use the new operator:
#Html.DropDownListFor(m => m.SelectedCities, Model.Cities, new { id = "cities", style = "width:320px;color:red;background-color:blue;" })
Edit:
As jbutler483 pointed out styling could be achieved through the following if you wish to use a css file (however if the style is a one off and is not used elsewhere in the site then inline styles are best):
Html.DropDownListFor(..., new { #class = "myclassname" } );

Related

''System.Web.Mvc.SelectListItem' does not contain a definition for 'string''

My Action method is given below:
public ActionResult Method()
{
var model = new PropertyDto();
if (!Request.Url.AbsoluteUri.Contains("?amp=1"))
{
if (DefaultCityID > 0)
model.CityID = DefaultCityID;
List<SelectListItem> Cities = cityService.GetMenuCitiesLite(1).Select(t => new SelectListItem { Text = t.Name, Value = t.ID.ToString() })
.OrderBy(o=>o.Text).ToList();
ViewBag.Cities = Cities;
ViewBag.CitiesIds = DefaultCityID;
}
ViewBag.Cities = cityService.GetMenuCitiesLite(SiteKeys.CountryID);
return View(model);
}
on the view dropdown list:
#Html.DropDownListFor(model => model.CityID, (List<SelectListItem>)ViewBag.Cities, "Select city", new RouteValueDictionary { { "data-rule-required", "true" }, { "data-msg-required", "*required" }, { "class", "form-control" }, { "id", "CityDropdown" } })
Now on the other partial view where i am getting the data of cities via viewbag is getting an exception:
#foreach (var item in ViewBag.Cities)
{
<li><a href="#(domain + item.SelfUrl)"><i class="fa fa-angle-double-
right"></i> #item.Name</a></li>
}
here i am getting the exception
Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''System.Web.Mvc.SelectListItem' does not contain a definition for 'SelfUrl''
HOW CAN I RESOLVE THIS?
SelectListItem which what item in ViewBag.Cities is, only has Text and Value and it doesn't have any of the properties you define on your models such as SelfUrl.
Simply don't use that model because you don't need it to render a list of links.
Use your own models such and initialize it like this instead of SelectListItem:
List<MyOwnModel> Cities = cityService.GetMenuCitiesLite(1).Select(t => new MyOwnModel { Text = t.Name, SelfUrl = t.ID.ToString(), Anything = "anything" })
You'll need to create the class of course:
public class MyOwnModel {
public string Text {get;set;}
public string SelfUrl {get;set;}
public string Antying {get;set;}
// put whatever you need here
}

Can I specify the default option for an "asp-items" list directly in the .cshtml?

I have an ASP.Net Core form like this:
<div class="form-group" id="DW_Q30_div">
<label>#Questions.Q30*</label>
<select asp-for="Answers.Q30" asp-items="DropdownValues.DeployEnvironments"></select>
</div>
This is the corresponding Dropdown list:
public class DropdownValues
{
public static List<SelectListItem> DeployEnvironments { get; } = new List<SelectListItem>
{
new SelectListItem { Value = "OnPremises", Text = "On Premises" },
new SelectListItem { Value = "Cloud", Text = "Cloud" }
};
...
Q: Is there any way I can specify the default item (for example, "Cloud" instead of "OnPremises") directly in the .cshtml markup itself?
As #LarryBud already commented change you code to this if you want select "Cloud" instead of "OnPremises:
public static List<SelectListItem> DeployEnvironments { get; } = new List<SelectListItem>
{
new SelectListItem { Value = "OnPremises", Text = "On Premises" },
new SelectListItem { Value = "Cloud", Text = "Cloud" , Selected=true }
};
for your edit you can use this code:
var defaultValue=...your value from db.
foreach(var item in DeployEnviroments)
{
if item.Value==defaultValue item.Selected=true;
}

How to correctly display radiobutton in asp.net mvc 5

I want to know what is the best way to display a group radio buttons in asp.net mvc 5 application.
Attempt 1:
#Html.RadioButton("SearchBy", "Name", true) <text> Name </text>
#Html.RadioButton("SearchBy", "Location") <text> Location</text>
[HttpPost]
public ActionResult Create(CoverLetterViewModel viewModel, string searchBy)
{//somecode}
Attempt 2:
//prop
public string SelectedRoleType { get; set; }
//view
<label>
#Html.RadioButtonFor(m => m.SelectedRoleType, "JobSeeker", new { #class = "js-radio", id = "" })
<span>Job Seeker</span>
</label>
<label>
#Html.RadioButtonFor(m => m.SelectedRoleType, "Referrer", new { #class = "js-radio", id = "" })
<span>Referrer</span>
</label>
//controller action
[HttpPost]
public ActionResult Create(CoverLetterViewModel viewModel)
{//somecode}
Attempt 3:
Now suppose I have 10 radiobutton, is there any efficient way to create radiobutton. I mean suppose I have a list of radiobuttonitem, Something like below
public List<SOME RADIBUTTON ITEM> radiobuttonlist {get;set;}
Question:
Can we somehow display radiobuttonsame way we handle List of Dropdown Item . Can we somehow avoid hardcoding "Referrer" AND "JobSeeker" text in view file.
Can we somehow display radiobuttonsame way we handle List of Dropdown Item .
No, there is no build-in Html Helper to render a list of radio buttons.
However, you can use simple foreach loop and render them one by one.
FYI: if value and key are same, you could just use List<string> instead of Dictionary<string, string>.
Action Method
public ActionResult Index()
{
var model = new SampleViewModel
{
Items = new Dictionary<string, string> {{"Referrer", "1"}, {"JobSeeker", "2"}}
};
return View(model);
}
ViewModel
public class SampleViewModel
{
public Dictionary<string, string> Items { get; set; }
public string SelectedItem { get; set; }
public SampleViewModel()
{
Items = new Dictionary<string, string>();
}
}
View
#foreach (var item in Model.Items)
{
<label>
#Html.RadioButtonFor(m => Model.SelectedItem, item.Value,
new { #class = "js-radio", id = "" })
<span>#item.Key</span>
</label>
}

DropDownListFor Inside EditorFor Not Selecting Values

I have found couple questions about my problem but none of them actually addresses the problem and gives alternative solutions to problem, thats why I am asking this again.
I am using strongly typed HTML Helpers and no ViewData and ViewBag for only page titles.
Here is my problem.
I have following viewmodel.
public class RegisterViewModel
{
public string Mail { get; set; }
public string Name { get; set; }
public ThreePartDatePickerViewModel ThreePartDateSelection { get; set; }
public RegisterViewModel()
{
ThreePartDateSelection = new ThreePartDatePickerViewModel();
}
}
Above viewmodel uses below viewmodel which basically holds data for 3 dropdownlist which are Day, Month and Year.
public class ThreePartDatePickerViewModel
{
public string Day { get; set; }
public string Year { get; set; }
public string Month { get; set; }
public IList<SelectListItem> Years { get; set; }
public IList<SelectListItem> Months { get; set; }
public IList<SelectListItem> Days { get; set; }
public ThreePartDatePickerViewModel()
{
var now = DateTime.Now;
Years = new List<SelectListItem>();
Months = new List<SelectListItem>();
Days = new List<SelectListItem>();
var empty = new SelectListItem { Text = "" };
Years.Add(empty);
Months.Add(empty);
Days.Add(empty);
foreach(var item in Enumerable.Range(0, 100).Select(x => new SelectListItem { Value = (now.Year - x).ToString(), Text = (now.Year - x).ToString() }))
Years.Add(item);
foreach(var item in Enumerable.Range(1, 12).Select(x => new SelectListItem { Value = x.ToString(), Text = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(x) }))
Months.Add(item);
foreach(var item in Enumerable.Range(1, 31).Select(x => new SelectListItem { Value = x.ToString(), Text = x.ToString() }))
Days.Add(item);
}
}
In the action method which returns RegisterViewModel to view, I am setting the Day,Month and Year properties of ThreePartDatePickerViewModel.
I have checked these values on runtime while views are generated and they are correct.
In my main view,
#model Bla.Bla.RegisterViewModel
<!-- Helpers for other properties -->
#Html.EditorFor(m => m.ThreePartDateSelection)
And my ThreePartDatePickerViewModel Editor Template is
#model Bla.Bla.ThreePartDatePickerViewModel
<div class="threePartDatePicker">
#Html.DropDownListFor(m => m.Day, Model.Days)
#Html.DropDownListFor(m => m.Month, Model.Months)
#Html.DropDownListFor(m => m.Year, Model.Years)
</div>
In my final rendered html, I have all the controls as expected. Dropdowns are rendered fine except the values I have set in action method are not selected.
If I switch from EditorTemplates to Partial Views, It starts working. Or If directly render dropdownlists inside my main view, instead of passing model to EditorFor, It again works.
It seems an old bug, not solved yet. it is reported here.
http://connect.microsoft.com/VisualStudio/feedback/details/654543/asp-net-mvc-possible-mvc-bug-when-working-with-editortemplates-and-drop-down-lists#details
I have to edit the editor template to set selected value as,
#{
//capture the selected list wherever it is. Here it passed in additionalViewData
SelectList tmpList, list = null;
ViewContext.ViewData.TryGetValue("list", out tmpList);
if (tmpList != null && tmpList.Count() > 0 && tmpList.SelectedValue == null)
{
list = new SelectList(tmpList, "Value", "Text", Model);
}
else
{
list = tmpList;
}
}
<div class="form-group">
#Html.DropDownListFor(m => m, list, attributes)
</div>
so I can work with select list in Editor Template as default behavior it should be.
I'm experiencing the same issue using a dropdownlist in an editor template. The selected value is not set even though I can see the correct value in the model. This is my workaround. It could be extended to work with other DropdownListFor methods.
public static class HtmlHelperExtensions
{
public static IHtmlString EditorDropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel)
{
var dropDown = SelectExtensions.DropDownListFor(htmlHelper, expression, selectList, optionLabel);
var model = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData).Model;
if (model == null)
{
return dropDown;
}
var dropDownWithSelect = dropDown.ToString().Replace("value=\"" + model.ToString() + "\"", "value=\"" + model.ToString() + "\" selected");
return new MvcHtmlString(dropDownWithSelect);
}
}

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

I am trying to build a Dropdownlist, but battling with the Html.DropDownList rendering.
I have a class:
public class AccountTransactionView
{
public IEnumerable<SelectListItem> Accounts { get; set; }
public int SelectedAccountId { get; set; }
}
That is basically my view model for now. The list of Accounts, and a property for returning the selected item.
In my controller, I get the data ready like this:
public ActionResult AccountTransaction(AccountTransactionView model)
{
List<AccountDto> accounts = Services.AccountServices.GetAccounts(false);
AccountTransactionView v = new AccountTransactionView
{
Accounts = (from a in accounts
select new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString(),
Selected = false
}),
};
return View(model);
}
Now the problem:
I am then trying to build the Drop down in my view:
<%=Html.DropDownList("SelectedAccountId", Model.Accounts) %>
I am getting the following error:
The ViewData item that has the key 'SelectedAccountId' is of type 'System.Int32' but must be of type 'IEnumerable'.
Why would it want me to return the whole list of items? I just want the selected value. How should I be doing this?
You have a view model to which your view is strongly typed => use strongly typed helpers:
<%= Html.DropDownListFor(
x => x.SelectedAccountId,
new SelectList(Model.Accounts, "Value", "Text")
) %>
Also notice that I use a SelectList for the second argument.
And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:
public ActionResult AccountTransaction()
{
var accounts = Services.AccountServices.GetAccounts(false);
var viewModel = new AccountTransactionView
{
Accounts = accounts.Select(a => new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString()
})
};
return View(viewModel);
}
Step-1: Your Model class
public class RechargeMobileViewModel
{
public string CustomerFullName { get; set; }
public string TelecomSubscriber { get; set; }
public int TotalAmount { get; set; }
public string MobileNumber { get; set; }
public int Month { get; set; }
public List<SelectListItem> getAllDaysList { get; set; }
// Define the list which you have to show in Drop down List
public List<SelectListItem> getAllWeekDaysList()
{
List<SelectListItem> myList = new List<SelectListItem>();
var data = new[]{
new SelectListItem{ Value="1",Text="Monday"},
new SelectListItem{ Value="2",Text="Tuesday"},
new SelectListItem{ Value="3",Text="Wednesday"},
new SelectListItem{ Value="4",Text="Thrusday"},
new SelectListItem{ Value="5",Text="Friday"},
new SelectListItem{ Value="6",Text="Saturday"},
new SelectListItem{ Value="7",Text="Sunday"},
};
myList = data.ToList();
return myList;
}
}
Step-2: Call this method to fill Drop down in your controller Action
namespace MvcVariousApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
RechargeMobileViewModel objModel = new RechargeMobileViewModel();
objModel.getAllDaysList = objModel.getAllWeekDaysList();
return View(objModel);
}
}
}
Step-3: Fill your Drop-Down List of View as follows
#model MvcVariousApplication.Models.RechargeMobileViewModel
#{
ViewBag.Title = "Contact";
}
#Html.LabelFor(model=> model.CustomerFullName)
#Html.TextBoxFor(model => model.CustomerFullName)
#Html.LabelFor(model => model.MobileNumber)
#Html.TextBoxFor(model => model.MobileNumber)
#Html.LabelFor(model => model.TelecomSubscriber)
#Html.TextBoxFor(model => model.TelecomSubscriber)
#Html.LabelFor(model => model.TotalAmount)
#Html.TextBoxFor(model => model.TotalAmount)
#Html.LabelFor(model => model.Month)
#Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")

Categories