I want to hide drop down according to class property value in asp.net mvc 3 razar view
You could apply a CSS class to the dropdown:
#Html.DropDownListFor(x => x.SelectedItemId, Model.Items, new { #class = "hidden" })
and then define the hidden CSS class:
.hidden {
display: none;
}
This hidden class could of course be applied dynamically based on some property value of the view model. For example you could write a custom HTML helper which could be used like so:
#Html.DropDownListFor(
x => x.SelectedItemId,
Model.Items,
Html.GetHtmlAttributes(Model.IsHidden)
)
where the GetHtmlAttributes is a custom extension method that you could write:
public static class HtmlExtensions
{
public static RouteValueDictionary GetHtmlAttributes(bool isHidden)
{
if (!isHidden)
{
return null;
}
return new RouteValueDictionary(new { #class = "hidden" });
}
}
Do you want to simply exclude the dropdown completely?
#if (!Model.DontShowDropdown)
{
#Html.DropDownListFor(....)
}
or, do you want to hide it?
Html.DropDownListFor(..., new { "style" = Model.DontShowDropDown ? "display:none" : "" };
You can use this ex:
#Html.DropDownList("mydropdown", new SelectList(new[] {
new SelectListItem{ Value = "0",Text="Item1"},
new SelectListItem{ Value = "1",Text="Item2"},
new SelectListItem{ Value = "2",Text="Item3"},
new SelectListItem{ Value = "3",Text="Item4"}
}, "Value", "Text", "2"), new
{
id = "mydropdown",
#class = "myddClass",
style = ""
})
in css add #mydropdown or .myddClass, then you can add display:none; in external css or add add it to inline css like style = "display:none;"
Related
Currently, I'm doing the following logic:
I have a Layout page where I need to display a Kendo.DropDown list.
I have created a Model:
public class CultureModel
{
public string Culture { get; set; }
public List<string> AvailableCultures { get; set; }
public CultureModel()
{
PopulateCulture();
}
private void PopulateCulture()
{
CultureModel cm = new CultureModel();
cm.AvailableCultures = new List<string>();
cm.AvailableCultures.Add("en-US");
cm.AvailableCultures.Add("de-DE");
cm.AvailableCultures.Add("es-ES");
}
}
And in my Layout I define the model: #model CultureModel
Then, I'm trying to render DisplayTemplate to show the dropdown:
#Html.DisplayFor(x => x.AvailableCultures, "_CultureSelector")
And my template is:
#model List<string>
<label for="culture">Choose culture:</label>
#(Html.Kendo().DropDownList()
.Name("culture")
)
Is that correct approach?
Thinking about your usecase by having a dropdown in the layout file, it would be fine to create your kendo dropdown with the following code directly in the layout file:
#{
#(Html.Kendo().DropDownList()
.Name("Cultures")
.DataTextField("Text")
.DataValueField("Value")
.BindTo(new List<SelectListItem>() {
new SelectListItem() {
Text = "en-US",
Value = "1"
},
new SelectListItem() {
Text = "de-DE",
Value = "2"
},
new SelectListItem() {
Text = "es-ES",
Value = "3"
}
})
)
}
Perhaps use a partialview to render the code in the layout for better code organizing and readability:
#Html.Partial("_CultureSelector")
I found the code on the telerik site: https://demos.telerik.com/aspnet-mvc/dropdownlist
Below is my DropDownList in view
<div class="col-xs-8 col-sm-8 col-md-4">
#Html.DropDownList("Status",new List<SelectListItem> { new SelectListItem{ Text="Active", Value = "Active" },new SelectListItem{ Text="InActive", Value = "InActive" }}, new { #class = "form-control" })
</div>
From DB value is coming either as "Active" or "Inactive" and dropdown has already these two value. And from my DB i'm assigning value in ViewBag.IsStatus.
Now suppose my value is coming "InAactive" from DB then how to assign this as Selected value in Dropdown rather than to show First dropdown by default as selected.
It's better to use DropDownListFor if you using MVC. But for your case just create SelectList and pass it to DropDownList. SelectList contructor has overload for selected value:
#{ //theese lines actually should be in controller.
var list = new List<SelectListItem>
{
new SelectListItem
{
Text="Active",
Value = "0"
}
,new SelectListItem
{
Text="InActive",
Value = "1"
}
}
}
//thats your code
<div class="col-xs-8 col-sm-8 col-md-4">
#Html.DropDownList("Status",new SelectList(list, "Value", "Text", ViewBag.IsStatus), new { #class = "form-control" })
</div>
If you have a model with Status property then simply assign this the value to the property (for example in controller):
Model
public class Model
{
public string Status {get;set;}
}
Controller
public ActionResult SomeAction()
{
//the value has to correspond to the Value property of SelectListItems
//that you use when you create dropdown
//so if you have new SelectListItem{ Text="Active", Value = "Active" }
//then the value of Status property should be 'Active' and not a 0
var model = new Model{Status = "Active"}
return this.View(model);
}
View:
#model Model
#Html.DropDownListFor(m=>m.Status,new List<SelectListItem> { new SelectListItem{ Text="Active", Value = "Active" },new SelectListItem{ Text="InActive", Value = "InActive" }}, new { #class = "form-control" })
I have an ASP.NET MVC 4 app. I'm not an MVC expert. In my view (.cshtml file), I have a Model that I'm binding to. In my model, I have a list of short values setup like this:
public void Load() {
List<short> options = new List<short>();
options.Add(1);
options.Add(3);
options.Add(7);
this.Options = options;
}
public List<short> Options = new List<short>() { get; set; }
public short? SelectedOption = null;
In my .cshtml file, I need to let the user choose one of the options from a drop down list. I see a bunch of HTML helpers, but I'm totally confused how to do this. How do I just display the drop down list and bind it back to my model? I am successfully binding to text boxes already, so I know I have my plumbing setup correctly. Its just this drop down list that's throwing me for a loop.
Thank you!
Suppose the object you are passing to the .cshtml view is your list which can be either passed through the ViewBag or as model.
Then depending in your requirement you can use multiple things to make a dropdown list out of which most preferable would be.
Html.DropDownList extention. Link to MSDN
so typical code would be
var options = Model ; //OR Viewbag.Options;
#Html.DropDownList(options.Select(o=>
new SelectListItem()
{
Text = o.ToString(),
Value = o.ToString()}
))
Also if you want to do it without any such specialized helper then
you can just create the HTML yourself.
<select>
#foreach(var o in Options){
<option value="#o.ToString()">#o.ToString()</option>
}
</select>
Small working snippet:
#model SelectListItem
#{
ViewBag.Title = "Index";
Layout = null;
List<SelectListItem> x = new List<SelectListItem>()
{
new SelectListItem { Text = "1", Value = "100", Selected = false },
new SelectListItem { Text = "2", Value = "200", Selected = true }
};
}
<html>
<head>
<title></title>
<script src="~/Scripts/jquery-1.8.2.js"></script>
</head>
<body>
#Html.DropDownListFor(model => model.Text, x)
</body>
</html>
<h2>Index</h2>
Above is the code of a view. You can pass a full model from the controller, when calling the View method, that will contain the list of elements you want to show. For the example, I simply created it on the fly (x list)
You can use this way for a dropdownlist..
In your controller
var sample = new List<SelectListItem> { new SelectListItem { Text = "--Select--", Value = "0" }, new SelectListItem { Text = "A", Value = "1" }, new SelectListItem { Text = "B", Value = "2" } };
ViewBag.something = sample;
In your View,
#Html.DropDownListFor(m => m.colname, (List<SelectListItem>)ViewBag.something , null, new { type = "text", Class = "", style = "" })
I'm using asp.net mvc 3.
I have this dropdownlist of countries and I want to add a placeholder for it. Here's my code:
#Html.DropDownList("country",
new SelectList(ViewBag.countries as System.Collections.IEnumerable,
"name", "name"), new { #class="chzn-select", #placeholder="-select-",
#style="width:160px;" } )
But the placeholder doesn't work, while the style works.
How do I set a placeholder for this?
PS. I just want to use #Html.DropDownList, not #Html.DropDownListFor
You could try this:
#Html.DropDownList("country", new SelectList(ViewBag.countries), "-select- ", new { #class="chzn-select", #style="width:160px;" })
A quick and (not so) dirty solution involving jQuery.
Instead of adding a dummy item at the start of the list, prepend a new option that is disabled. The main advantage is that you don't have to mess with a dummy item in your list, and most important, you won't be able to select that dummy item in the page:
#Html.DropDownList("yourName", yourSelectList, new { #class = "form-control select-add-placeholder" })
Then somewhere after:
$(".select-add-placeholder").prepend("<option value='' disabled selected>Select an option...</option>");
Which looks like:
In your collection ViewBag.Countries just insert a dummy record at the from of the collection with the name "-select-". You should be able to force the selected item with an alternate constructor like this:
#Html.DropDownList("country",
new SelectList(ViewBag.countries as System.Collections.IEnumerable,
"name", "name", "-select-"), new { #class="chzn-select", #style="width:160px;" } )
#Html.DropDownListFor(m => m.SelectedProductIDs,
Model.AvaliableProducts.ToSelectList("ID","Name"),
new { #class = "chzn-select",
data_placeholder="Please select a product" })...
Please see in more details : http://code.stylenet.ca/mvc3-data-placeholder-html5-attribute/
I can see that there is not an easy answer.
I´ve developed a simple solution but it gives some work. This will work for DropDownList and DropDownListFor
First create an Extension Class where ever you want. (Must be Static with static methods)
And Then add the following extension method
public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper,string name, IEnumerable<SelectListItem> selectList, string optionLabel, bool disableLabel)
{
MvcHtmlString mvc = htmlHelper.DropDownList(name, selectList, optionLabel);
if (disableLabel)
{
string disabledOption = mvc.ToHtmlString();
int index = disabledOption.IndexOf(optionLabel);
disabledOption = disabledOption.Insert(index - 1, " disabled");
return new MvcHtmlString(disabledOption);
}
else
{
return mvc;
}
}
Now Note the this Extension only add a new attribute, the disableLabel
This will check if you want to disable or not the label.
Now You let´s go to view´s side
first declare that you want to use the extension class you have created
ex: #using WF.Infrastructure.Extension;
Now you use like it: #Html.DropDownList("Unidade", lstUnidade, "Text of Option Disabled",true)
Note: if you want it to work with DropDownListFor, just add another extension method for your Extension Class with this signature:
public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel,bool disableLabel)
PS: If you declare your extension methods in a separated project like me, you will need to add assemblies ( System.Web.Mvc, System.Web)
and in your Extension Class you will need to declare:
using System.Web.Mvc;
using System.Web.Mvc.Html;
Maybe if you want, try this:
#Html.DropDownList("country",null,"-SELECT-",new { #class="chzn-select",#style="width:160px;" })
Try this:
#Html.DropDownList("MetadataId", (MultiSelectList)ViewData["category"], "All Categories",
new { #class = "chk_dropdown d-none", #id = "categories", multiple = "multiple" })
Try this
#Html.DropDownListFor(m => m.SelectedProductIDs, Model.AvaliableProducts.ToSelectList("ID","Name"), new { #class = "chzn-select", data-placeholder="Please select a product" })
Or
#Html.DropDownListFor(model => model.SelectedItemID, new SelectList(Model.employeeList, "Value", "Text"), new Dictionary<string, object> { { "data-placeholder", "Choose a sandbox..." }, { "class", "chzn-select" }, { "style", "width:200px;" } })
Best way
#Html.DropDownListFor(m => m.SelectedProductIDs,
Model.AvaliableProducts.ToSelectList("ID","Name"),
"Please select a product",
new { #class = "chzn-select"})
#Html.DropDownListFor(m => m.SelectedProductIDs,
Model.AvaliableProducts.ToSelectList("ID","Name"),
"Please select a product",
new {enter code here #class = "chzn-select"})
I have a Parent model with a list of child models. In the view I'm rendering the children using a template like so
#Html.EditorFor(model => model.ChildItems)
In the child model template I have this drop downlist
#Html.DropDownListFor(model => model.Quantity,
new SelectList(new[] { 1,2,3,4,5,6,7,8,9,10 }))
but I don't know how to set the selected item.
Most examples I see are simple controller create the list, set the selected and pass to the view.
Unless I am, in the controller to do something like
ViewBag["Child_1_SelectedItem"] = children[0].Quantity
ViewBag["Child_2_SelectedItem"] = children[1].Quantity
which I don't see how I'd get the view to understand that at all.
There is another overload on the SelectList constructor which accepts the selected item, so you're almost there with your second code snippet
int[] array = { 1, 2, 3 };
var list = new SelectList(array, 1);
Given this, could you change your code to:
#Html.DropDownListFor(model => model.Quantity,
new SelectList(new[] { 1,2,3,4,5,6,7,8,9,10 }, model.Quantity))
Edit:
It seems you can't access the lambda parameter outside of the first argument (which makes sense), but you should be able to do this (assuming Model is the same type as model, subtle difference):
#Html.DropDownListFor(model => model.Id,
new SelectList(new[] { 1,2,3,4,5,6,7,8,9,10 }, Model.Id))
Or, using a simple variable:
#{
int selectedQuantity = Model.Quantity;
}
#Html.DropDownListFor(model => model.Id,
new SelectList(new[] { 1,2,3,4,5,6,7,8,9,10 }, selectedQuantity))
You would typically do :
var quantities = new List<SelectListItem>(new[] {
new SelectListItem {
Selected = true,
Text="1",
Value="1"
},
new SelectListItem {
Text="2",
Value="2"
}
....
And then:
#Html.DropDownListFor(model => model.Quantity, quantities)
Seems annoying but you could build this on the controller like this:
var q = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<SelectListItem> list = new List<SelectListItem>();
foreach (var item in q)
{
if(children[item].Quantity)// dunno what is in this property...
{//if Quantity is bool you could directly set Selected then..
list.Add(new SelectListItem { Selected = true, Text = item.ToString() });
} else {
list.Add(new SelectListItem { Text = item.ToString() });
}
}
And then pass your list down to the view. OR you could just do this in a #{..} code block in the view itself.