Q: How to set width for #Html.DropDownList (and not in css)?
#Html.DropDownList("ListId", String.Empty, new {style="width: 250px;"}) #* no go!*#
The second argument of the DropDownList helper must be an IEnumerable<SelectListItem>. You are passing a string (an empty one to be more precise). So in order to use this helper you will have to respect its signature:
#Html.DropDownList(
"ListId",
Enumerable.Empty<SelectListItem>(),
new { style = "width: 250px;" }
)
Obviously generating an empty dropdown list is of little use. You probably have a view model (you should by the way) that you want to use to bind to:
#Html.DropDownList(
"ListId",
Model.MyList,
new { style = "width: 250px;" }
)
and of course because you have a view model you should prefer to use the DropDownListFor helper:
#Html.DropDownListFor(
x => x.ListId,
Model.MyList,
new { style = "width: 250px;" }
)
and finally to avoid cluttering your HTML with styles you should use an external CSS:
#Html.DropDownListFor(
x => x.ListId,
Model.MyList,
new { #class = "mycombo" }
)
where in your external CSS you would define the .mycombo rule:
.mycombo {
width: 250px;
}
Now you have what I consider a proper code.
You should use the View Model approach. However the lazy way out is just to give the 2nd parameter a null.
#Html.DropDownList("ListId", null, new {style="width: 250px;"})
#Html.DropDownListFor(model => model.Test,
new SelectList(new List<YourNamespace.Modelname>(), "Id", "Name"),
null, new { #id = "ddlTest", #style="width: 250px;" })
There is a jquery technique that allows you to set the width without having to deal with the #Html.DropDownList constructor.
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#ListId").width(300);
});
</script>
Related
I am want to have a text area with multiple lines and a value in MVC3. I can't seem to define a textareafor or an editorfor that has a #Value attribute which I can set. I want to have something like
#Html.TextAreaFor(x => x.model, 10, 15, new{#Value="try"})
Also, I want to be able to do this in the view because the default value will depend on an attribute of another model used within the same view.
Any thoughts please.
The textarea html element does not support the value attribute. So you can't set its value using #Html.TextAreaFor.
So what you have to do is this:
#model MvcApplication.Models.Model
#{
if (1 > 2) // your logic here
{
Model.Description = "value1";
}
else
{
Model.Description = "value2";
}
}
#Html.TextAreaFor(model => model.Description, new { #rows = "10", #cols = "15" })
Let the html helper handle the rendering.
Use Telerik control
Html.Telerik().EditorFor(model => model.Description)
.Name("Editor")
.HtmlAttributes(new { style = "height:400px" })
.Encode(false)
.Value((String)ViewBag.Contents)
.Render();
I am using webgrid to displat list of records.
My view is tightly coupled with IEnumerable.
#model IEnumerable<Models.SitesConfig.Configuration>
I am binding webgrid with Model.
var grid = new WebGrid(Model, rowsPerPage: 50);
I am trying to format a column using #helper method. #helper method taking a parametr of type Models.SitesConfig.Configuration.
When I try to load the view, I am getting invalid arguments error.
This is my view.
#model IEnumerable<Models.SitesConfig.SiteConfiguration>
#section Styles {
<link href="#Url.Content("~/Content/SatelliteSite.css")" rel="stylesheet" type="text/css" />
}
#{
ViewBag.Title = "List of Satellite Sites";
}
#helper FormatTemplateColors(Models.SitesConfig.SiteConfiguration item)
{
#String.Format(
"Border: {0} <br/>Link: {1} <br/>Text: {2}",
item.BorderColor != null ? item.BorderColor.Name : string.Empty,
item.LinkColor != null ? item.LinkColor.Name : string.Empty,
item.TextColor != null ? item.TextColor.Name : string.Empty)
}
#{
var grid = new WebGrid(Model, rowsPerPage: 50);
}
<div>
#grid.GetHtml(columns: grid.Columns(
grid.Column("Template",
style: "color-column-width",
format:(item) => #FormatTemplateColors(item)
)
)
</div>
Can somebody help me on this.
In the format lambda the item parameter is an instance of the WebGridRow class (in a form of dynamic) where the Value property holds the actual item.
So you need to write:
format:(item) => #FormatTemplateColors(item.Value)
SideNote if you wan't to output html you need to use the Html.Raw helper. So modify your helper to:
#helper FormatTemplateColors(Models.SitesConfig.SiteConfiguration item)
{
#Html.Raw(String.Format(...
}
I'm using ASP.NET MVC 3, and just ran into a 'gotcha' using the DropDownListFor HTML Helper.
I do this in my Controller:
ViewBag.ShippingTypes = this.SelectListDataRepository.GetShippingTypes();
And the GetShippingTypes method:
public SelectList GetShippingTypes()
{
List<ShippingTypeDto> shippingTypes = this._orderService.GetShippingTypes();
return new SelectList(shippingTypes, "Id", "Name");
}
The reason I put it in the ViewBag and not in the model (I have strongly typed models for each view), is that I have a collection of items that renders using an EditorTemplate, which also needs to access the ShippingTypes select list.
Otherwise I need to loop through the entire collection, and assign a ShippingTypes property then.
So far so good.
In my view, I do this:
#Html.DropDownListFor(m => m.RequiredShippingTypeId, ViewBag.ShippingTypes as SelectList)
(RequiredShippingTypeId is of type Int32)
What happens is, that the value of RequiredShippingTypeId is not selected in the drop down.
I came across this: http://web.archive.org/web/20090628135923/http://blog.benhartonline.com/post/2008/11/24/ASPNET-MVC-SelectList-selectedValue-Gotcha.aspx
He suggests that MVC will lookup the selected value from ViewData, when the select list is from ViewData. I'm not sure this is the case anymore, since the blog post is old and he's talking about MVC 1 beta.
A workaround that solves this issue is this:
#Html.DropDownListFor(m => m.RequiredShippingTypeId, new SelectList(ViewBag.ShippingTypes as IEnumerable<SelectListItem>, "Value", "Text", Model.RequiredShippingTypeId.ToString()))
I tried not to ToString on RequiredShippingTypeId at the end, which gives me the same behavior as before: No item selected.
I'm thinking this is a datatype issue. Ultimately, the HTML helper is comparing strings (in the Select List) with the Int32 (from the RequiredShippingTypeId).
But why does it not work when putting the SelectList in the ViewBag -- when it works perfectly when adding it to a model, and doing this inside the view:
#Html.DropDownListFor(m => m.Product.RequiredShippingTypeId, Model.ShippingTypes)
The reason why this doesn't work is because of a limitation of the DropDownListFor helper: it is able to infer the selected value using the lambda expression passed as first argument only if this lambda expression is a simple property access expression. For example this doesn't work with array indexer access expressions which is your case because of the editor template.
You basically have (excluding the editor template):
#Html.DropDownListFor(
m => m.ShippingTypes[i].RequiredShippingTypeId,
ViewBag.ShippingTypes as IEnumerable<SelectListItem>
)
The following is not supported: m => m.ShippingTypes[i].RequiredShippingTypeId. It works only with simple property access expressions but not with indexed collection access.
The workaround you have found is the correct way to solve this problem, by explicitly passing the selected value when building the SelectList.
This might be silly, but does adding it to a variable in your view do anything?
var shippingTypes = ViewBag.ShippingTypes;
#Html.DropDownListFor(m => m.Product.RequiredShippingTypeId, shippingTypes)
you can create dynamic viewdata instead of viewbag for each dropdownlist field for complex type.
hope this will give you hint how to do that
#if (Model.Exchange != null)
{
for (int i = 0; i < Model.Exchange.Count; i++)
{
<tr>
#Html.HiddenFor(model => model.Exchange[i].companyExchangeDtlsId)
<td>
#Html.DropDownListFor(model => model.Exchange[i].categoryDetailsId, ViewData["Exchange" + i] as SelectList, " Select category", new { #id = "ddlexchange", #class = "form-control custom-form-control required" })
#Html.ValidationMessageFor(model => model.Exchange[i].categoryDetailsId, "", new { #class = "text-danger" })
</td>
<td>
#Html.TextAreaFor(model => model.Exchange[i].Address, new { #class = "form-control custom-form-control", #style = "margin:5px;display:inline" })
#Html.ValidationMessageFor(model => model.Exchange[i].Address, "", new { #class = "text-danger" })
</td>
</tr>
}
}
ViewModel CompanyDetail = companyDetailService.GetCompanyDetails(id);
if (CompanyDetail.Exchange != null)
for (int i = 0; i < CompanyDetail.Exchange.Count; i++)
{
ViewData["Exchange" + i]= new SelectList(companyDetailService.GetComapnyExchange(), "categoryDetailsId", "LOV", CompanyDetail.Exchange[i].categoryDetailsId);
}
I was just hit by this limitation and figured out a simple workaround. Just defined extension method that internally generates SelectList with correct selected item.
public static class HtmlHelperExtensions
{
public static MvcHtmlString DropDownListForEx<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression,
IEnumerable<SelectListItem> selectList,
object htmlAttributes = null)
{
var selectedValue = expression.Compile().Invoke(htmlHelper.ViewData.Model);
var selectListCopy = new SelectList(selectList.ToList(), nameof(SelectListItem.Value), nameof(SelectListItem.Text), selectedValue);
return htmlHelper.DropDownListFor(expression, selectListCopy, htmlAttributes);
}
}
The best thing is that this extension can be used the same way as original DropDownListFor:
#for(var i = 0; i < Model.Items.Count(); i++)
{
#Html.DropDownListForEx(x => x.Items[i].CountryId, Model.AllCountries)
}
There is an overloaded method for #html.DropdownList for to handle this.
There is an alternative to set the selected value on the HTML Dropdown List.
#Html.DropDownListFor(m => m.Section[b].State,
new SelectList(Model.StatesDropdown, "value", "text", Model.Section[b].State))
I was able to get the selected value from the model.
"value", "text", Model.Section[b].State this section the above syntax adds the selected attribute to the value loaded from the Controller
I would like to change the background color of the first row in a WebHelper WebGrid for MVC without the use of JQuery.
Any Thoughts?
#model IEnumerable<MyViewModel>
#{
var indexedModel = Model.Select((item, index) => new { Element = item, Index = index });
var grid = new WebGrid(indexedModel);
}
#grid.GetHtml(
columns: grid.Columns(
grid.Column(
columnName: "item.MyProperty",
header: "Myproperty",
format:
#<text>
<div#Html.Raw(item.Index == 0 ? " class=\"firstRow\"" : "")>
#item.Element.MyProperty
</div>
</text>
)
)
)
and in your CSS:
.firstRow {
background-color: Red;
}
One suggestion could be in each columns's format parameter, use an if-else situation based on a distinct variable that will wrap the data in a span with a css. A bit cumbersome but should work.
For this reason some JQuery would potentially be easier.
I need to check a checkbox by default:
I tried all of these, nothing is checking my checkbox -
#Html.CheckBoxFor(m => m.AllowRating, new { #value = "true" })
#Html.CheckBoxFor(m => m.AllowRating, new { #checked = "true" })
#Html.CheckBoxFor(m => m.AllowRating, new { #checked = true })
#Html.CheckBoxFor(m => m.AllowRating, new { #checked = "checked"})
You should set the AllowRating property to true, preferably in the controller or model.
Like other inputs, the checkbox's state reflects the value of the property.
This works for me:
<input id="AllowRating" type="checkbox" #(Model.AllowRating?"checked='checked'":"") style="" onchange="" />
If you really wants to use HTML Helpers:
#Html.CheckBoxFor(m => m.AllowRating, new { #checked = Model.AllowRating})
Also take into account that if m.AllowRating is false, it will fail to set to status checked in your examples.
The syntax in your last line is correct.
#Html.CheckBoxFor(x => x.Test, new { #checked = "checked" })
That should definitely work. It is the correct syntax. If you have an existing model and AllowRating is set to true then MVC will add the checked attribute automatically. If AllowRating is set to false MVC won't add the attribute however if desired you can using the above syntax.
You can do this with #Html.CheckBoxFor():
#Html.CheckBoxFor(m => m.AllowRating, new{#checked=true });
or you can also do this with a simple #Html.CheckBox():
#Html.CheckBox("AllowRating", true) ;
you set AllowRating property to true from your controller or model
#Html.CheckBoxFor(m => m.AllowRating, new { #checked =Model.AllowRating })
<input type="checkbox" #( Model.Checked == true ? "checked" : "" ) />
only option is to set the value in the controller, If your view is Create then in the
controller action add the empty model, and set the value like,
Public ActionResult Create()
{
UserRating ur = new UserRating();
ur.AllowRating = true;
return View(ur);
}
If we set "true" in model, It'll always true. But we want to set option value for my checkbox we can use this. Important in here is The name of checkbox "AllowRating", It's must name of var in model if not when we post the value not pass in Database.
form of it:
#Html.CheckBox("NameOfVarInModel", true) ;
for you!
#Html.CheckBox("AllowRating", true) ;
I had the same issue, luckily I found the below code
#Html.CheckBoxFor(model => model.As, htmlAttributes: new { #checked = true} )
Check Box Checked By Default - Razor Solution
I did it using Razor , works for me
Razor Code
#Html.CheckBox("CashOnDelivery", CashOnDelivery) (This is a bit or bool value) Razor don't support nullable bool
#Html.CheckBox("OnlinePayment", OnlinePayment)
C# Code
var CashOnDelivery = Convert.ToBoolean(Collection["CashOnDelivery"].Contains("true")?true:false);
var OnlinePayment = Convert.ToBoolean(Collection["OnlinePayment"].Contains("true") ? true : false);