DropdownListFor default value - asp.net-mvc-3

Is there a simple way to add a "--Please select--" default option to a DropDownListFor in MVC 3?

So, I did something like this:
#Html.DropDownListFor(model => model.Dessert,
new SelectList(Model.AvailableDesserts, "DessertID", "DessertName"),
"---Select A Dessert ---")
Seems to work pretty well. Dessert in my viewmodel is the one selected by the user. AvailableDesserts is a collection of ones to pick from.

I have a couple extension methods on SelectList
public static SelectList PreAppend(this SelectList list, string dataTextField, string selectedValue, bool selected=false)
{
var items = new List<SelectListItem>();
items.Add(new SelectListItem() { Selected = selected, Text = dataTextField, Value = selectedValue });
items.AddRange(list.Items.Cast<SelectListItem>().ToList());
return new SelectList(items, "Value", "Text");
}
public static SelectList Append(this SelectList list, string dataTextField, string selectedValue, bool selected=false)
{
var items = list.Items.Cast<SelectListItem>().ToList();
items.Add(new SelectListItem() { Selected = selected, Text = dataTextField, Value = selectedValue });
return new SelectList(items, "Value", "Text");
}
public static SelectList Default(this SelectList list,string DataTextField,string SelectedValue)
{
return list.PreAppend(DataTextField, SelectedValue, true);
}
Then my razor looks like:
#Html.DropDownListFor(m=>m.SelectedState,
Model.StateList().Default("Select One",""))

Hi what about trying this (in case you use DisplayFor method)
private IEnumerable<SelectListItem> AddDefaultOption(IEnumerable<SelectListItem> list, string dataTextField, string selectedValue)
{
var items = new List<SelectListItem>();
items.Add(new SelectListItem() { Text = dataTextField, Value = selectedValue});
items.AddRange(list);
return items;
}
Then just add this code to your Controller
//lambda expression binding
ViewBag.YourList = db.YourTable.Select(x => x).ToList().Select(x => new SelectListItem
{
Value = x.Id.ToString(),
Text = x.DisplayName.ToString()
});
ViewBag.YourList = AddDefaultOption(ViewBag.YourList, "Select One...", "null", true);
And finally at the View you could display a dropdown, combobox just like this
<div class="editor-label">
Your Label
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.ForeignKey, (IEnumerable<SelectListItem>)ViewBag.YourList)
</div>

I wanted to set the default value to whatever was passed in as a Url Parameter called SiteType:
<div class="form-group">
#Html.LabelFor(model => model.Type, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Type, ChangeOrderSite.SiteTypeNames.Select(s => new SelectListItem { Text = s.Value, Value = s.Key.ToString(), Selected = s.Key.ToString() == Request["SiteType"] }), new { #class = "control-label col-md-2" })
#Html.ValidationMessageFor(model => model.Type)
</div>
</div>
My drop down is a list of Site Types.

I like the following method:
#Html.DropDownListFor(m => m.SelectedId, new SelectList(Model.Items, "Id", "Name"), new SelectListItem() { Text = "None", Value = "", Selected = true }.Text, new { #class = "form-control search-select-input btn btn-block btn-outline-secondary dropdown-toggle p-1" })
Where Items is an IEnumerable of type you want to display in the dropdown. And you can change out whatever bootstrap classes you want in the last parameter.
This way allows you to set a default label and specify the value of the label if needed.

Related

How to create drop down list in mvc

This is my controller
[AllowAnonymous]
public ActionResult Register()
{
ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
return View();
}
This is my Create view part
<div class="form-group">
#Html.Label("Select Your User Type", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#*#Html.DropDownList("Name")*#
#Html.DropDownList("Name",(SelectList)ViewBag.Name )
</div>
</div>
i can load the form with drop down. but when I am try to save the record it gives an error "The ViewData item that has the key 'Name' is of type 'System.String' but must be of type 'IEnumerable'."
Do this:
[AllowAnonymous]
public ActionResult Register()
{
var items = new List<SelectListItem>();
foreach (var role in context.Roles)
{
items.Add(new SelectListItem {Text = role.Name, Value = role.Value});
}
var result = new SelectList(items);
ViewBag.Name = result;
return View();
}
View
#Html.DropDownList("Name",ViewBag.Name)
But can I suggest that you avoid ViewBag and use strongly typed models.
Look here

Populate DropDownListFor and default value is guid parameter

I have populated a DropDownListFor with all the correct values. I'm passing a Guid parameter, but don't know how to set the default value to that Guid.
View
<div class="form-group">
#Html.LabelFor(model => model.Parent)
#Html.DropDownListFor(model => model.Parent, new SelectList(Model.AllParents, "Id", "Name"), string.Empty, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Parent)
</div>
ViewModel
public class ParentViewModel
{
public List<Parent> AllParents { get; set; }
[DisplayName("Parent")]
public Guid? ParentId { get; set; }
}
Controller
[HttpGet]
public ActionResult Create(Guid? id)
{
var parentViewModel = new ParentViewModel
{
AllParents = _Service.GetAll().ToList()
};
return View(parentViewModel);
}
}
You need to replace string.Empty with "Default value do you want"
#Html.DropDownListFor(model => model.Parent, new SelectList(Model.AllParents, "Id", "Name"), "Default value is here here", new { #class = "form-control" })

Bind Telerik DDL

I am trying to bind a Telerik DropDownList.
View Code:
<div>#( Html.Telerik().DropDownList()
.Name("ddlCounty")
.HtmlAttributes(new { style = "width:200px;" })
.SelectedIndex(0)
.BindTo(new SelectList((IEnumerable<MvcNew.Models.tbl_Country>)ViewData["ListCountries"], "Value", "Text")) )
</div>
Controller Code:
List<SelectListItem> lst_Country = new List<SelectListItem>();
var Countries = (from m in DBContext.tbl_Countries
select new SelectListItem{ Text = m.Country__Name.ToString(), Value = m.Country_ID.ToString() });
ViewBag.ListCountries = new SelectList(Countries);
return View();
I am getting the below error
Unable to cast object of type 'System.Web.Mvc.SelectList' to type 'System.Collections.Generic.IEnumerable`1[MvcNew.Models.tbl_Country]'.
I have changed a code like this and it's worked
var clientIDs = DBContext.tbl_Countries
List<SelectListItem> items = new List<SelectListItem>();
foreach (var t in clientIDs)
{
SelectListItem s = new SelectListItem();
s.Text = t.Country__Name.ToString();
s.Value = t.Country__Name.ToString();
items.Add(s);
}
ViewBag.ListCountries = items;

MVC3 EditorFor readOnly

I want to make readOnly with EditorFor in edit page.
I tried to put readonly and disabled as:
<div class="editor-field">
#Html.EditorFor(model => model.userName, new { disabled = "disabled", #readonly = "readonly" })
</div>
However, it does not work. How can I make to disable edit this field?
Thank you.
The EditorFor html helper does not have overloads that take HTML attributes. In this case, you need to use something more specific like TextBoxFor:
<div class="editor-field">
#Html.TextBoxFor(model => model.userName, new
{ disabled = "disabled", #readonly = "readonly" })
</div>
You can still use EditorFor, but you will need to have a TextBoxFor in a custom EditorTemplate:
public class MyModel
{
[UIHint("userName")]
public string userName { ;get; set; }
}
Then, in your Views/Shared/EditorTemplates folder, create a file userName.cshtml. In that file, put this:
#model string
#Html.TextBoxFor(m => m, new { disabled = "disabled", #readonly = "readonly" })
This code is supported in MVC4 onwards
#Html.EditorFor(model => model.userName, new { htmlAttributes = new { #class = "form-control", disabled = "disabled", #readonly = "readonly" } })
For those who wonder why you want to use an EditoFor if you don`t want it to be editable, I have an example.
I have this in my Model.
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0: dd/MM/yyyy}")]
public DateTime issueDate { get; set; }
and when you want to display that format, the only way it works is with an EditorFor, but I have a jquery datepicker for that "input" so it has to be readonly to avoid the users of writting down wrong dates.
To make it work the way I want I put this in the View...
#Html.EditorFor(m => m.issueDate, new{ #class="inp", #style="width:200px", #MaxLength = "200"})
and this in my ready function...
$('#issueDate').prop('readOnly', true);
I hope this would be helpful for someone out there.
Sorry for my English
You can do it this way:
#Html.EditorFor(m => m.userName, new { htmlAttributes = new { disabled = true } })
I know the question states MVC 3, but it was 2012, so just in case:
As of MVC 5.1 you can now pass HTML attributes to EditorFor like so:
#Html.EditorFor(x => x.Name, new { htmlAttributes = new { #readonly = "", disabled = "" } })
Try using:
#Html.DisplayFor(model => model.userName) <br/>
#Html.HiddenFor(model => model.userName)
Here's how I do it:
Model:
[ReadOnly(true)]
public string Email { get { return DbUser.Email; } }
View:
#Html.TheEditorFor(x => x.Email)
Extension:
namespace System.Web.Mvc
{
public static class CustomExtensions
{
public static MvcHtmlString TheEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null)
{
return iEREditorForInternal(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
private static MvcHtmlString iEREditorForInternal<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
{
if (htmlAttributes == null) htmlAttributes = new Dictionary<string, object>();
TagBuilder builder = new TagBuilder("div");
builder.MergeAttributes(htmlAttributes);
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
string labelHtml = labelHtml = Html.LabelExtensions.LabelFor(htmlHelper, expression).ToHtmlString();
if (metadata.IsRequired)
labelHtml = Html.LabelExtensions.LabelFor(htmlHelper, expression, new { #class = "required" }).ToHtmlString();
string editorHtml = Html.EditorExtensions.EditorFor(htmlHelper, expression).ToHtmlString();
if (metadata.IsReadOnly)
editorHtml = Html.DisplayExtensions.DisplayFor(htmlHelper, expression).ToHtmlString();
string validationHtml = Html.ValidationExtensions.ValidationMessageFor(htmlHelper, expression).ToHtmlString();
builder.InnerHtml = labelHtml + editorHtml + validationHtml;
return new MvcHtmlString(builder.ToString(TagRenderMode.Normal));
}
}
}
Of course my editor is doing a bunch more stuff, like adding a label, adding a required class to that label as necessary, adding a DisplayFor if the property is ReadOnly EditorFor if its not, adding a ValidateMessageFor and finally wrapping all of that in a Div that can have Html Attributes assigned to it... my Views are super clean.
Create an EditorTemplate for a specific set of Views (bound by one Controller):
In this example I have a template for a Date, but you can change it to whatever you want.
Here is the code in the Data.cshtml:
#model Nullable<DateTime>
#Html.TextBox("", #Model != null ? String.Format("{0:d}", ((System.DateTime)Model).ToShortDateString()) : "", new { #class = "datefield", type = "date", disabled = "disabled" #readonly = "readonly" })
and in the model:
[DataType(DataType.Date)]
public DateTime? BlahDate { get; set; }
Old post I know.. but now you can do this to keep alignment and all looking consistent..
#Html.EditorFor(model => model.myField, new { htmlAttributes = new { #class = "form-control", #readonly = "readonly" } })
I use the readonly attribute instead of disabled attribute - as this will still submit the value when the field is readonly.
Note: Any presence of the readonly attribute will make the field readonly even if set to false, so hence why I branch the editor for code like below.
#if (disabled)
{
#Html.EditorFor(model => contact.EmailAddress, new { htmlAttributes = new { #class = "form-control", #readonly = "" } })
}
else
{
#Html.EditorFor(model => contact.EmailAddress, new { htmlAttributes = new { #class = "form-control" } })
}
<div class="editor-field">
#Html.EditorFor(model => model.userName)
</div>
Use jquery to disable
<script type="text/javascript">
$(document).ready(function () {
$('#userName').attr('disabled', true);
});
</script>
i think this is simple than other by using [Editable(false)] attribute
for example:
public class MyModel
{
[Editable(false)]
public string userName { get; set; }
}

ASP.NET MVC 3 - Html.DropDownList for Enumerated values

I'm new to ASP.NET MVC 3. I'm trying to display some options in a drop down list. The options will mimic values in an enum. The enum has the following three values:
public enum Gender
{
Male = 0,
Female = 1,
NotSpecified=-1
}
I am trying to generate the following HTML
<select>
<option value="0">Male</option>
<option value="1">Female</option>
<option value="2">Not Specified</option>
</select>
I'm trying to do this with Razor, but i'm a bit lost. Currently I have:
#Html.DropDownList("relationshipDropDownList", WHAT GOES HERE?)
Please note, I cannot edit the enum. Thank you for your help!
something like this...
//add this to your view model
IEnumerable<SelectListItem> genders = Enum.GetValues(typeof(Gender))
.Cast<Gender>()
.Select(x => new SelectListItem
{
Text = x.ToString(),
Value = x.ToString()
});
#Html.DropDownList("relationshipDropDownList", Model.genders)
There is an answer to the same question here
The accepted answer has an extension method to convert the enum into a selectlist, which can be used like this
In the controller
ViewBag.Relationships = Gender.ToSelectList();
in the partial
#Html.DropDownList("relationshipDropDownList", ViewBag.Relationships)
#Html.DropDownList("relationshipDropDownList", Model.GenderSelectList);
However, I would rather use DropDownListFor to avoid using magic strings:
#Html.DropDownListFor(m => m.relationshipDropDownList, Model.GenderSelectList);
and in the ViewModel you'd build your SelectListItems
public static List<SelectListItem> GenderSelectList
{
get
{
List<SelectListItem> genders = new List<SelectListItem>();
foreach (Gender gender in Enum.GetValues(typeof(Gender)))
{
genders.Add(new SelectListItem { Text = gender.ToString(), Value = gender.ToString("D"), Selected = false });
}
return genders;
}
}
public enum EnumGender
{
Male = 0,
Female = 1,
NotSpecified = -1
}
#Html.DropDownList("relationshipDropDownList", (from EnumGender e in Enum.GetValues(typeof(EnumGender))
select new SelectListItem { Value = ((int)e).ToString(), Text = e.ToString() }), "select", new { #style = "" })
//or
#Html.DropDownList("relationshipDropDownList", (from EnumGender e in Enum.GetValues(typeof(EnumGender))
select new SelectListItem { Value = ((int)e).ToString(), Text = e.ToString() }), null, new { #style = "" })

Resources