Using #HTML.labelFor helper in ASP.NET MVC - asp.net-mvc

I am creating a view for a model in ASP.NET MVC. I am using #HTML.LabelFor
#Html.LabelFor(m => m.Name, htmlAttributes: new { #class = "control-label col-md-2" })
but I am getting this error:
Error CS0411
The type arguments for method 'LabelExtensions.LabelFor<TModel, TValue>(HtmlHelper, Expression<Func<TModel, TValue>>, object)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

This is a strange error, but doing what it asks to do can help. Try specifying the type arguments explicitly:
#Html.LabelFor<YourModelType, TypeOfNameProperty>(m => m.Name, htmlAttributes: new { #class = "control-label col-md-2" })
Note: my experience (that knows lots of errors like this) tells me that this error will vanish after some time. During this time, you may use the code above. It's not more than a workaround.

Related

Exception in Dropdown list of .Net MVC 4 using Entity Framework

I am trying to create a dropdown list in my .Net MVC project.
This is how my Controller looks like
public ActionResult Register()
{
ViewBag.Name = new SelectList(context.AspNetRoles.ToList(), "Id", "Name");
return View();
}
And this is how my View looks like
<div class="form-group">
#Html.LabelFor(model => model.Name, "Name", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("Name", ViewBag.Name as SelectList)
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
The problem what i am facing is that when i execute my code i get this Excpetion
The ViewData item that has the key 'Name' is of type 'System.String' but must be of type 'IEnumerable'.
As i am Newbie to MVC,I dont know why i am getting this exception.Any help would be appreciated.
Thanks in advance.
Happy Coding!

Razor has three different ways to set "class" attribute

Here is the code generated from "Add View" wizard in ASP .NET MVC5 project:
<div class="form-group">
#Html.LabelFor(model => model.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.City, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.City, "", new { #class = "text-danger" })
</div>
</div>
As you can see, there are three different ways the "class" attribute is set on an html control. Why this anomaly? Also, is one preferred over the other? Regards.
The 1st and the 3rd are the same. The 1st is a naming parameter. You can use this way for more clarity but it is not required.
But the 2nd example pass html attributes into another object which agregates it. And you cannot use this way for two previous. In the MVC sources this object is converted to the KeyValuePair:
if (additionalViewData != null)
{
foreach (KeyValuePair<string, object> kvp in TypeHelper.ObjectToDictionary(additionalViewData))
{
viewData[kvp.Key] = kvp.Value;
}
}
They are all the same!
I prefer this one htmlAttributes: new { #class = "control-label col-md-2" } because it shows the parameter name clearly.Otherwise, the other two options are all good.

How to use an instance produced by Binding in an ActionResult

This is a general concept question dealing with the Edit life-cycle in MVC.
As I understand it, the Edit GET action pulls the requested instance from the db context and ends by passing that instance to the Edit View (where the instance is referred to as the view model).
The Edit View uses stuff like this:
#Html.HiddenFor(model => model.SomethingIDoNOTWantEdited)
<div class="form-group">
#Html.LabelFor(model => model.SomethingIDoWantEdited, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SomethingIDoWantEdited, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SomethingIDoWantEdited, "", new { #class = "text-danger" })
</div>
</div>
to display some or all of the properties of the view model so that the user can change the values if needed.
When the user clicks the submit button the Edit POST Action is called, and when used with something like this
[HttpPost]
public ActionResult Edit([Bind(Include = "Id, SomethingIDoWantEdited, SomethingIDoNOTWantEdited")] MyClass viewModel)
Makes a bright shiny new object of type MyClass called viewModel.
Now, I know I could do a query on the context and get the current object in the db that has that Id, and then copy all the fields from viewModel to the existing one before marking the original as modified and then calling SaveChanges(). That's not too bad when there are only a few properties to copy, but when there are lots of them it becomes cumbersome.
Is there a better way to get the items the user changed written back to the database?

How do I add a ID to my textbox or dropdown list

In my view I have textbox and dropdown menu , I am trying to add an Class so that I can apply bootstrap themes to my fields. This is my code:
<div class="form-group">
#Html.LabelFor(model => model.ID, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ID", String.Empty)
#Html.ValidationMessageFor(model => model.ID)
</div>
</div>
How do I declare class to this class="from-controller" I tried this #Html.DropDownList("ID", new {class="test"}) but I get an error. Can anyone tell me why.
The second argument of the DropDownList Method is IEnumerable<SelectListItem>, so your dropdown has to look like this:
#Html.DropDownList("ID", new SelectList(Model.CollectionOfIds, "DataValueField", "DataTextField"),
new { #class= "from-controller" })
First parameter is name not an ID. If you want to specify an id you have to do it same way as specifying a class.
#Html.DropDownList("ddlName", new SelectList(Model.Items, "Key", "Value"), "Please select", new { #class = "className", #id="yourId" })
new SelectList(Model.Items, "Key", "Value") will work for
Dictionary<int, string>
type
First :
class is a reserved keyword of c# language. When you want use a reserved keyword like variable name in C# you should put the # sign before variable name to the compiler ignore the fact that it's also a keyword.
in your case your must add # before class keyword
new {#class="test"})
Second :
There are not definition for Html.DropDownList(string, string) or Html.DropDownList(string, string, object)
the second parameter must be an IEnumerable
If you want set an empty list (I don't undersant why you set a String.Empy value) use Enumerable.Empty()
#Html.DropDownList("ID", Enumerable.Empty<SelectListItem>())

Has the behavior for DataAnnotations in asp.net mvc 3 changed?

I have a Model with a property
[ReadOnly(true)]
public decimal BodyMassIndex { get; private set; }
In my View when I call
#Html.EditorForModel()
I still get a standard editable textbox for that property
Why is this? if the textbox is still editable whats the point of this DataAnnotation Attibute?
Brad Wilson's post
That is not a DataAnnotation attribute. Notice it's in the System.ComponentModel namespace. Data Annotations are in the System.ComponentModel.DataAnnotations namespace.
However, this is a case where we could consider supporting it. But what exactly did you expect to happen and why do you want this?
you can use
#Html.TextBoxFor(x=> x.ModelProperty, new { #readonly="readonly"})
From what I understand of your question and the comments on other answers, you simply want to display the BodyMassIndex, not have it as editable.
If this is the case, use #Html.DisplayFor rather than #Html.EditorFor.
AFAIK the ReadOnlyAttribute is for property of class. From MSDN
Members that are marked with the ReadOnlyAttribute set to true or that do not have a Set method
cannot be changed. Members that do not have this attribute or that are marked with the
ReadOnlyAttribute set to false are read/write, and they can be changed. The default is No.
So you use this inside your classes to prevent modification to the properties. (at least the meaning I give to that attribute)
If you want a textbox readonly use something like that
#Html.TextBox("MyText", "my text", new { #readonly="readonly" })
the # first of readonly tell the compiler to bybass the reserved word
This works in Vs2013 C# with Bootstrap 3.
<div class="form-group">
#Html.LabelFor(model => model.PasswordHash, htmlAttributes: new { #class = "control-label col-md-3" })
<div class="col-md-6">
#Html.EditorFor(model => model.PasswordHash, new { htmlAttributes = new { #class = "form-control", #readonly="readonly" } })
#Html.ValidationMessageFor(model => model.PasswordHash, "", new { #class = "text-danger" })
</div>
</div>

Resources