I want to following html code using asp.net mvc 3 razor html helper:
<input type="text" .... . placeholder="Login" data-icon="user" />
I have try this one:
#Html.TextBoxFor(m => m.UserName, new { placeholder = "Login", data-icon = "user" })
or
#Html.TextBoxFor(m => m.UserName, new { placeholder = "Login", #data-icon = "user" })
Displayed Error:
Invalid anonymous type members declaration.
This might due to dash in data-icon not taken as attributes. How could I add data-icon attributes in text box field.
try this
#Html.TextBoxFor(m => m.UserName, new { placeholder = "Login", data_icon = "user" })
Yes, you can't write like that but you can write your own Extension to solve this problem. Here is the sample code:
public static MvcHtmlString MyInput(this HtmlHelper htmlHelper, string name, string value, string icon)
{
var attrs = new Dictionary<string,object>();
attrs.Add("data-icon", icon);
return htmlHelper.TextBox(name, name, value, attrs);
}
Or you can also use in razor like this:
#{
var attrs = new Dictionary<string, object>();
attrs.Add("placeholder","Login");
attrs.Add("data-icon","user");
}
#Html.TextBoxFor(m => m.UserName, attrs)
Plz don't forget to mark it's right answer if it helps you :-)
This is really the same as vNext's second alternative, but if you prefer to write it in-line:
#Html.TextBoxFor(m => m.UserName, new Dictionary<string, object> { { "placeholder", "Login" }, { "data-icon", "user" } })
Related
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
when I use the following actionlink:
<%: Html.ActionLink("Study Cases", "Index", "CourseCases", new { id = Model.ID }, new { #class = "t-button", #style = "width:240px; color:white; text-align:center" })%>
The url address in the browser is:
http://localhost:11111/CourseCases/Index/9
How can I change it so the url will be
http://localhost:11111/CourseCases?courseId=9
It works when I use:
return RedirectToAction("Index", "CourseCases", new { courseId = id });
in the controller.
Thanks in adance.
Like this:
<%= Html.ActionLink(
"Study Cases",
"Index",
"CourseCases",
new { courseId = Model.ID },
new {
#class = "t-button",
#style = "width:240px; color:white; text-align:center"
}
) %>
The reason why your code generates http://localhost:11111/CourseCases/Index/9 is because the {id} is used by the default route that was generated when you created your ASP.NET MVC 3 application, so when you specify id = Model.ID it will match the route pattern definition in your Global.asax which is {controller}/{action}/{id} thus you get CourseCases/Index/9.
I know on the Razor View file, we can do something like this
#Html.TextBox("username", null, new { maxlength = 20, autocomplete = "off" })
However, I am hoping to create a model for the MVC that can be used to create a form with explicitly defined the size and max length of the textboxes. I try [StringLength(n)] on top of the properties of the model, but that seems to only do the validation ratherh set the size of the textbox.
Is there anyway that we can define the length of the text field as a data annotation on top of a property of a model?
So ultimately, we could just create the whole form by using razor to map to a model rather than explicitly pick up the model properties one by one in order to set the textbox size.
Here is a outline of a custom helper that uses StringLengthAttribute.
public class MyModel
{
[StringLength(50)]
public string Name{get; set;}
}
public MvcHtmlString MyTextBoxFor<TModel, TProperty>(this HtmlHelper<TModel> helper,
Expression<Func<TModel, TProperty>> expression)
{
var attributes = new Dictionary<string, Object>();
var memberAccessExpression = (MemberExpression)expression.Body;
var stringLengthAttribs = memberAccessExpression.Member.GetCustomAttributes(
typeof(System.ComponentModel.DataAnnotations.StringLengthAttribute), true);
if (stringLengthAttribs.Length > 0)
{
var length = ((StringLengthAttribute)stringLengthAttribs[0]).MaximumLength;
if (length > 0)
{
attributes.Add("size", length);
attributes.Add("maxlength", length);
}
}
return helper.TextBoxFor(expression, attributes);
}
Does this not work?
public class ViewModel
{
[StringLength(20)]
public string UserName {get;set;}
}
In the View:
#Html.TextBoxFor(x => x.UserName, new {autocomplete = "off"})
or:
#Html.EditorFor(x => x.UserName)
I find that I prefer my views to just Call Html.EditorFor(...). This means that the Editor and Display templates decide the fate of controls in my view, such that my view code gets cleaned up a lot - it just has html and generic requests for editors.
The following link gives a working sample of getting this working in an Editor Template
https://jefferytay.wordpress.com/2011/12/20/asp-net-mvc-string-editor-template-which-handles-the-stringlength-attribute/
I'm using similar in my String.cshtml Editor Template (goes in Shared/EditorTemplates ).
#model object
#using System.ComponentModel.DataAnnotations
#{
ModelMetadata meta = ViewData.ModelMetadata;
Type tModel = meta.ContainerType.GetProperty(meta.PropertyName).PropertyType;
}
#if(typeof(string).IsAssignableFrom(tModel)) {
var htmlOptions = new System.Collections.Generic.Dictionary<string, object>();
var stringLengthAttribute = (StringLengthAttributeAdapter)ViewData.ModelMetadata.GetValidators(this.ViewContext.Controller.ControllerContext).Where(v => v is StringLengthAttributeAdapter).FirstOrDefault();
if (stringLengthAttribute != null && stringLengthAttribute.GetClientValidationRules().First().ValidationParameters["max"] != null)
{
int maxLength = (int)stringLengthAttribute.GetClientValidationRules().First().ValidationParameters["max"];
htmlOptions.Add("maxlength", maxLength);
if (maxLength < 20)
{
htmlOptions.Add("size", maxLength);
}
}
htmlOptions.Add("class", "regular-field");
<text>
#Html.TextBoxFor(m => m, htmlOptions)
</text>
}
else if(typeof(Enum).IsAssignableFrom(tModel)) {
//Show a Drop down for an enum using:
//Enum.GetValues(tModel)
//This is beyond this article
}
//Do other things for other types...
Then my model is annotated such as:
[Display(Name = "Some Field", Description = "Description of Some Field")]
[StringLength(maximumLength: 40, ErrorMessage = "{0} max length {1}.")]
public string someField{ get; set; }
And my View simply calls:
<div class="editor-label">
#Html.LabelWithTooltipFor(model => model.something.someField)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.something.someField)
#Html.ValidationMessageFor(model => model.something.someField)
</div>
You might also notice that my String.cshtml Editor Template also auto-magically handles Enum's, but that is starting to digress from the current topic, so I nixed that code, I'll just say here that the String Editor Template can pull extra weight, and likely google has someting on that https://www.google.com/search?q=string+editor+template+enum
Label With Tooltip For is a custom HTML helper that just drops the description into the label title, for more information on mouse over for every label.
I'd recommend this approach if you want to do this in an Editor Template.
I have created a default MVC 3 project (using razor), in order to demonstrate an issue.
On the login page, there is a line:
#Html.TextBoxFor(m => m.UserName)
if I change this to:
#Html.TextBoxFor(m => m.UserName, new { title = "ABC" })
Then the it is rendered as (with a title attribute):
<input data-val="true" data-val-required="The User name field is required." id="UserName" name="UserName" title="ABC" type="text" value="" />
However, if I make it an EditorFor:
#Html.EditorFor(m => m.UserName, new { title = "ABC" })
Then it gets rendered (without a title attribute) as:
<input class="text-box single-line" data-val="true" data-val-required="The User name field is required." id="UserName" name="UserName" type="text" value="" />
So in summary, the title attribute is lost when I use EditorFor.
I know that the second parameter for TextBoxFor is called htmlAttributes, and for EditorFor it is additionalViewData, however I've seen examples where EditorFor can render attributes supplied with this parameter.
Can anyone please explain what I am doing wrong, and how I can have a title attribute when using EditorFor?
I think I found a little nicer solution to it. EditorFor takes in additionalViewData as a parameter. If you give it a parameter named "htmlAttributes" with the attributes, then we can do interesting things with it:
#Html.EditorFor(model => model.EmailAddress,
new { htmlAttributes = new { #class = "span4",
maxlength = 128,
required = true,
placeholder = "Email Address",
title = "A valid email address is required (i.e. user#domain.com)" } })
In the template (in this case, EmailAddress.cshtml) you can then provide a few default attributes:
#Html.TextBox("",
ViewData.TemplateInfo.FormattedModelValue,
Html.MergeHtmlAttributes(new { type = "email" }))
The magic comes together through this helper method:
public static IDictionary<string, object> MergeHtmlAttributes<TModel>(this HtmlHelper<TModel> htmlHelper, object htmlAttributes)
{
var attributes = htmlHelper.ViewData.ContainsKey("htmlAttributes")
? HtmlHelper.AnonymousObjectToHtmlAttributes(htmlHelper.ViewData["htmlAttributes"])
: new RouteValueDictionary();
if (htmlAttributes != null)
{
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(htmlAttributes))
{
var key = property.Name.Replace('_', '-');
if (!attributes.ContainsKey(key))
{
attributes.Add(key, property.GetValue(htmlAttributes));
}
}
}
return attributes;
}
Of course you could modify it to render the attributes as well if you are doing raw HTML:
public static MvcHtmlString RenderHtmlAttributes<TModel>(this HtmlHelper<TModel> htmlHelper, object htmlAttributes)
{
var attributes = htmlHelper.ViewData.ContainsKey("htmlAttributes")
? HtmlHelper.AnonymousObjectToHtmlAttributes(htmlHelper.ViewData["htmlAttributes"])
: new RouteValueDictionary();
if (htmlAttributes != null)
{
foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(htmlAttributes))
{
var key = property.Name.Replace('_', '-');
if (!attributes.ContainsKey(key))
{
attributes.Add(key, property.GetValue(htmlAttributes));
}
}
}
return MvcHtmlString.Create(String.Join(" ",
attributes.Keys.Select(key =>
String.Format("{0}=\"{1}\"", key, htmlHelper.Encode(attributes[key])))));
}
In MVC3 you can add a title (and other htmlAttributes) using this kind of workaround if you create a custom EditorFor template. This case is prepared for the value to be optional, editorFor calls are not required to include the object additionalViewData
#Html.EditorFor(m => m.UserName, "CustomTemplate", new { title = "ABC" })
EditorTemplates/CustomTemplate.cshtml
#{
string s = "";
if (ViewData["title"] != null) {
// The ViewData["name"] is the name of the property in the addtionalViewData...
s = ViewData["title"].ToString();
}
}
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { title = s })
I did something very similar to include an optional class in an EditorTemplate. You can add as many items to the addtionalViewData as you like but you need to handle each on in the EditorFor template.
You may take a look at the following blog post which illustrates how to implement a custom metadata provider and use data annotations on your view model in order to define html properties such as class, maxlength, title, ... This could then be used in conjunction with the templated helpers.
this is my Model1 class
namespace chetan.Models
{
public class Model1
{
public string selectedItem { get; set; }
public IEnumerable<SelectListItem> items { get; set; }
}
}
this is my controller class
public class HomeController : Controller
{
private rikuEntities rk = new rikuEntities();
public ActionResult Index()
{
var model = new Model1
{
items = new[]
{
new SelectListItem { Value = "Theory", Text = "Theory" },
new SelectListItem { Value = "Appliance", Text = "Appliance" },
new SelectListItem { Value = "Lab", Text = "Lab" }
}
}; return View(model);
}
public ActionResult viewToController(Model1 m)
{
string getSelectedName = m.selectedItem;
return Content(getSelectedName);
}
}
this is my view...
#using (Html.BeginForm("viewToController", "Home"))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>emp</legend>
<div class="editor-field">
#Html.DropDownListFor(x => x.selectedItem,
new SelectList(Model.items, "Value", "Text"))
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
i want to add a drop downlist and i want to use selected value in viewToController action of homeController. and there is also one error in View page is "an expression tree may not contain dynamic operation" in (x=>x.selectedItem). Please solve my problem .
I don't understnad what you exactly need. You want to dynamicly add items to the drop down from the database?
I'm big fan of jQuery. You can do everything what you want with HTML using jQuery. So if you are looking how to automaticly add items to the drop down, take look at this: How do I add options to a DropDownList using jQuery?