I want to add a class to a selectfor
but I get an error
#Html.SelectFor(m => m.foo, optionLabel: null, new { #class = "foo12" })
With a text box it works:
#Html.TextBoxFormattedFor(m => m.foo, new { #class = "foo" })
Error I get:
Named argument specifications must appear after all fixed arguments have been specified.
The error is self-explanatory -- any named arguments (in this case "optionLabel") have to come after unnamed ones. So instead of this:
#Html.SelectFor(m => m.foo, // 1
optionLabel: null, // 2
new { #class = "foo12" } // 3
)
I guess you probably want this:
#Html.SelectFor(m => m.foo, // 1
optionLabel: null, // 2
htmlAttributes: new { #class = "foo12" } // 3
)
Edit
Surely you mean DropDownListFor, and not "SelectListFor"? You need to provide the options as well. Something like this:
#{
var selectList = new SelectListItem[]
{
new SelectListItem { Text = "text", Value = "value" },
};
}
#Html.DropDownListFor(m => m.foo,
selectlist: selectlist,
htmlAttributes: new { #class = "foo" }
)
Related
I want to make a form where the form is required only if a field of another model is set. When trying to do the following:
#model MyApp.ViewModels.ModelVM
...
#Html.Label("Tickets", new { #class = "control-label" })
#Html.TextBoxFor(model => model.FooBar,
new
{
#class = "form-control",
#required = (model => model.Foo == 1 ? true : false),
})
I get the compiler error "Cannot assign lambda expression to anonymous type"
How can I get the result I want?
An excerpt from Microsoft docs regarding anonymous types and exception you've had:
" Anonymous types contain one or more public
read-only properties...The expression that is used
to initialize a property cannot be null, an
anonymous function, or a pointer type."
Using only the check to initialize the property should do the trick.
#required = model.Foo == 1
You can't use lambda expression to the anonymous type inside HTML helper (i.e. htmlAttributes). To use conditional required attribute as HTML attribute, you can do it using ternary operator like this:
#Html.TextBoxFor(model => model.FooBar, Model.Foo == 1 ?
(object)new { #class = "form-control", #required = "required" } :
(object)new { #class = "form-control" })
Or using an if block:
#if (Model.Foo == 1)
{
#Html.TextBoxFor(model => model.FooBar, new { #class = "form-control", #required = "required" })
}
else
{
#Html.TextBoxFor(model => model.FooBar, new { #class = "form-control" })
}
Note: required HTML attribute for <input> elements is a boolean attribute, which false value is indicated by absence of the attribute, and the presence of that attribute simply indicates true value:
The values "true" and "false" are not allowed on boolean attributes.
To represent a false value, the attribute has to be omitted
altogether.
Related issue:
Conditional Html attribute using razor #html helpers
Given the following MVC5 code:
#Html.DropDownList(name: "Enhanced_Rijndael_AlgorithmID", optionLabel: null, selectList: EnhancedRijndaelAvailableHashAlgorithmList.Select(item => new SelectListItem
{
Value = item.RecordID.ToString(),
Text = item.HashAlgorithm,
Selected = "select" == item.RecordID.ToString()
}), htmlAttributes: new { #class = "form-control" })
Is it possible to set the "selected value" of this list?
The only thing I can think of is somehow setting the Selected value in the SelectListItem set.
Here is the what Ive come up with after being reminded of the DropDownListFor
#Html.DropDownListFor(expression: r => r.AlgorithmID, selectList: EnhancedRijndaelAvailableHashAlgorithmList.Select(item => new SelectListItem
{
Value = item.RecordID.ToString(),
Text = item.HashAlgorithm,
Selected = "select" == item.RecordID.ToString()
}),
htmlAttributes: new { #class = "form-control" }, optionLabel: "Algorithm")
Below View Code. when i click on Create button without Selecting Activity. it is not showing validation message. i am using Required attribute in Model Class
<div class="form-group">
#Html.LabelFor(model => model.TransactionTypeID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.TransactionTypeID, new SelectList(ViewBag.GetT, "TransactionTypeID", "TransactionType"), "--Select--", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TransactionTypeID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ActivityID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.ActivityID, new SelectList(ViewBag.GetA, "ActivityID", "ActivityName"), "--Select--", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ActivityID, "", new { #class = "text-danger" })
</div>
</div>
//Controller code
public ActionResult Create()
{
List<TransactionTypeMaster> T = new DATransactionTypeMaster().GetListAll();
ViewBag.GetT = T;
List<ActivityMaster> A = new DAActivityMaster().GetListAll();
ViewBag.GetA = A;
return View();
}
Can Any One Help on this. Need To Know Where i m going Wrong
when i click on Create button without Selecting Activity. it is not showing validation message. i am using Required attribute in Model Class
try giving the default '--Select--' options in your drop downs a value of 0.
In your model, make sure your drop down value is set to '[Required]' and also give it the attribute:
[Range(1, Int32.MaxValue, ErrorMessage = "Must Select A Value")]
basically letting it only accept values > 0
I think you TransactionTypeID is int, make that Nullable that would fix this issue. Currently it doesn't work because by default it might be sending zero as a value by using null, it would send null when user doesn't touch this field.
Hi I am trying to convert the text entered in textbox to uppercase, but I am not getting the output,please help.
#Html.TextBoxFor(model => model.PanNumber, new { #class = "form-control", #onkeyup = "InputToUpper(this);" })
This should work (remove #onkeyup = "InputToUpper(this);" from the TextBoxFor method)
$('#PanNumber').keyup(function() {
var text = $(this).val();
$(this).val(text.toUpperCase());
});
if you are using "#editorfor" text box then try
#Html.EditorFor(model => model.PanNumber.Alias, new {
htmlAttributes = new { #class = "upper-case" }
})
I am using the Kendo grid in my ASP.Net MVC application. If I have the following grid definition,
#(Html.Kendo().Grid(Model) //Bind the grid to ViewBag.Products
.Name("grid")
.Columns(columns =>
{
columns.Bound(p => p.FullName);
columns.Bound(p => p.MyEnum)
})
.Groupable()
.Pageable()
.Sortable()
.Scrollable(scr => scr.Height(600))
.Filterable()
)
where one of the column is an Enum. My enum definition is:
public enum MyEnum
{
[Display(AutoGenerateField = false, Name = "My enum 1", Description = "My Enum 1")]
EnumOne,
[Display(Name = "My Enum 2")]
EnumTwo
}
How do I make it display "My Enum 1" or "My Enum 2" for each row?
Thanks in advance!
I recently ran into this problem and solved it by using
var someArrayOfValueAndText = new[] {new {
Id = 0, Description = "Foo"
}, new {
Id = 1, Description = "Bar"
}
.Columns(c.ForeignKey(m=> m.MyEnum, someArrayOfValueAndText, "Id","Description"))
instead of the .Bound method
I created an helper class containing some extension methods a while back:
public static class EnumExtensions
{
public static string GetDisplayName(this Enum enu)
{
var attr = GetDisplayAttribute(enu);
return attr != null ? attr.Name : enu.ToString();
}
public static string GetDescription(this Enum enu)
{
var attr = GetDisplayAttribute(enu);
return attr != null ? attr.Description : enu.ToString();
}
private static DisplayAttribute GetDisplayAttribute(object value)
{
Type type = value.GetType();
if (!type.IsEnum)
{
throw new ArgumentException(string.Format("Type {0} is not an enum", type));
}
// Get the enum field.
var field = type.GetField(value.ToString());
return field == null ? null : field.GetCustomAttribute<DisplayAttribute>();
}
}
It contains two methods for extracting the Name and Description of a Display attribute. The display name:
columns.Bound(p => p.MyEnum.GetDisplayName())
And for a description:
columns.Bound(p => p.MyEnum.GetDescription())
You have to add a using statement in your Web.config or in your view.
Update
What if you create a property for it in your model:
public string MyEnumName
{
get { return MyEnum.GetDisplayName(); }
}
Now you should be able to use:
columns.Bound(p => p.MyEnumName);
Henk's solution is good. But you can use filtering capability if you use ClientTemplate:
col.Bound(m => m.MyEnum) // this provides you filtering
.ClientTemplate("#: MyEnumName #") // this shows a name of enum
For more information about kendo ui templates see: http://docs.telerik.com/kendo-ui/framework/templates/overview
I use #user1967246 method and would like to explain more how to i do.
i created array in top of my kendo grid
var statusLikeEntityStatus = new[]
{
new {Id = 0, Status = EntityStatus.Passive},
new {Id = 1, Status = EntityStatus.Active},
new {Id = 2, Status = EntityStatus.Draft},
new {Id = 3, Status = EntityStatus.ReadyToLive},
new {Id = -1, Status = EntityStatus.Freezed},
new {Id = -2, Status = EntityStatus.Blocked}
};
Then i use ForeignKey property instead of Bound.
columns.ForeignKey(m => m.Status, statusLikeEntityStatus, "Id", "Status").Title(Resources.General.Status);
Here is my columns attribute
.Columns(columns =>
{
columns.Bound(m => m.InventoryID).Title("Id");
columns.Bound(m => m.ERPCode).Title(Resources.Products.ProductCode);
columns.Bound(m => m.Price).Title(Resources.Products.ListPrice);
columns.Bound(m => m.Discount).Title(Resources.Products.
columns.Bound(m => m.Stock).Title(Resources.Products.TotalStock); // todo: Resources
columns.ForeignKey(m => m.Status, statusLikeEntityStatus, "Id", "Status").Title(Resources.General.Status);
columns.Command(commandConf =>
{
commandConf.Edit();
commandConf.Destroy();
});
})
Hope it will help to you.