how to show some text in html.LabelFor? - asp.net-mvc

I am doing int like this:
Hello <%= Html.LabelFor(user => user.UserName)%>
But iam getting not a value which is in Property but something strange like this:
Hello User Name,
How can do it to give some value in label out?

Add DataAnnotations to your model/viewmodel:
public class Customer
{
[Display(Name = "Email Address", Description = "An email address is needed to provide notifications about the order.")]
public string EmailAddress { get; set; }
[Display(ResourceType=typeof(DisplayResources), Name="LName", Description="LNameDescription")]
public string LastName { get; set; }
}
Source: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute(v=VS.95).aspx
If you don't provide a display name by the DisplayAttribute then Html.EditorFor(...) uses the properties name, spliting it on upper case letters:
PropertyName --> Label text
Email --> Email
EmailAdress --> Email Address

The reason for this is because Html.LabelFor will do just that - create a label for the property. In this case, it is producing a label of 'User Name' since the property name is UserName.
You just need to look at the model (or whatever your passing to the view) to return the property value: Html.Encode(Model.UserName)
Update (since this was nearly 3 years ago but people have recently upvoted):
You can just use <%: Model.UserName %> to get the HTML encoded value (<%= writes it as raw and <%: writes it encoded).
If you're using a Razor view engine, then #Model.Username will write it out already encoded.

Related

MVC Razor retrieve Description text from Model in HTML helper class

Okay I have searched it long enough to not find this anywhere on the net. So here is my question, in asp.net MVC (5.1) razor the default helper we can use DisplayNameFor to get the Name value from Display attribute is there anything similar for retrieving Description?
[Display(Name = "First Name", Description="What is your first name")]
public string FirstName { get; set; }
E.g.
#Html.DisplayNameFor(model=>model.FirstName)
Instead use LabelFor and try below code.
#Html.LabelFor(m => m.FirstName,
new{title=ModelMetadata.FromLambdaExpression<Models.Profile, string>
(m => m.FirstName, ViewData).Description})

Validation error - The field Int32 must be a number - on string property

I have a funny problem and I did not find the cause.
In asp.net MVC application I have a form that saves some simple information. All fields can be stored neatly except one. This field (string) returns validation error "The Int32 field must be a number" but only if the sentences in the text contains a single digit number. For example, if the sentence is as follows:
"Some simple sentence that contains the number 3" I'll get a validation error - "The Int32 field must be a number", if that same sentence transformed into:
"Some simple sentence that contains the number 30" or "Some simple sentence that contains a 30%" - no errors
Field property from a model:
[Display(Name = "Some name")]
[StringLength(500, ErrorMessage = "You can enter up to 500 characters.")]
public string Akcija { get; set; }
Next to that field I have one (string) field with the same property characteristics, and it is working properly.
Clip from view:
<div>
#Html.TextAreaFor(m => m.Akcija, new { style = "width:500px; height:100px;" })
#Html.ValidationMessageFor(m => m.Akcija)
</div>
It can not be simpler than that, but the problem is around here.
Do you have any suggestions?
Edit:
If I keep trying to save the changes it will be saved to the database regardless of the validation error. It seems to me that this is a JavaScript validation error or a bug
Edit 2 - Generated HTML:
<textarea cols="20" data-val="true" data-val-number="The field Int32 must be a number." data-val-required="The Int32 field is required." id="Akcija" name="Akcija" rows="2" style="width:500px; height:100px;">
Web aplikacije i siteovi 3 sa 30% sniženja
I do not know where it comes from - this attribute "data-val-number =" The field Int32 must be a number. '" And " data-val-required = "The Int32 field is required.'"
I'm not in the code imposed these rules
Try tagging the property with [DataType(DataType.MultilineText)]. Maybe that will make it explicit to the TextAreaFor helper.
If anyone ever run into this problem, the workaround is to use Html.EditorFor how it follows:
First: Add validation attribute [DataType (DataType.MultilineText)] to model property
so that model property looks like this:
[Display(Name = "Some name")]
[StringLength(500, ErrorMessage = "You can enter up to 500 characters.")]
[DataType(DataType.MultilineText)]
public string Akcija { get; set; }
Secondly: Make Template for Html.EditorFor.
Template create in a folder Views/Shared/EditorTemplates - if there is no folder EditorTemplates, make it.
In the folder EditorTemplates create a partial view named with the name of the model property.
In my case it is: akcija.cshtml
In this view should be forwarded the value of the model property and you must include the HTML that defines the field of view so that the template, in my case, look like this:
#model System.String
#if(!string.IsNullOrEmpty(Model))
{
<textarea name="Akcija" style="width:500px;height:100px;">#Model.ToString() </textarea>
}
else
{
<textarea name="Akcija" style="width:500px;height:100px;">#Model</textarea>
}
Third In your View change Html.TextAreaFor in Html.EditorFor and put a reference to your template. Html.EditorFor, in my case, now looks like this:
<div>
#Html.EditorFor(m => m.Akcija, "akcija")
#Html.ValidationMessageFor(m => m.Akcija)
</div>
And that's it, problem solved.
Note: When naming template and objects within the template and the template it self, note the naming convention. Note that my template is named with small letter and in html template there is no id attribute for html object.
I hope that this will help someone
Use a nullable int/Int32.
public int? mobilequantity { get; set; }
or
public Int32? mobilequantity {get; set;}
that works on my form

mvc [DataType(DataType.EmailAddress) no validation

I'm using this code on an email field:
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
[DataType(DataType.EmailAddress)] does not work (validation does not occur no at a server not on the client side).
I am not sure if I should implement myself a Custom Attribute or I can use one included with MVC 3.
Could you please suggest me a solution for creating a custom attribute in case I need to.
I read also about some additional extensions, example
http://nuget.org/packages/DataAnnotationsExtensions.MVC3
Would you suggest it to me?
You could use the usual DataAnnotations library by just using [EmailAddress]
using System.ComponentModel.DataAnnotations;
[Required]
[EmailAddress]
public String Email { get; set; }
Also just for reference, here's the regular expression version of this validation:
[RegularExpression(#"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)#([A-Za-z0-9]+)(([\.\-‌​]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", ErrorMessage = "Email is not valid")]
public String Email {get; set;}
Best of luck!
At the moment I have solved my problem using
DataAnnotationsExtensions
it just works, you add their library with NuGet
using DataAnnotationsExtensions;
[Required]
[DataType(DataType.EmailAddress)]
[Email]
public string Email { get; set; }
It looks like all the answers focus on the Data Model while this issue can be affected by the View itself.
The following on MVC .NET 4.5 is working alright:
Data model:
[Required]
[DataType(DataType.EmailAddress)]
[DisplayName("Email")]
public string Email { get; set; }
Razor View:
#Html.LabelFor(model => model.Email)
#Html.EditorFor(model => model.Email)
Note: do not need to add [EmailAddress] attribute. If you use [DataType(DataType.EmailAddress)] along with #Html.EditorFor() in your View, you should be fine.
As highlighted with rich.okelly, at the end you want your input rendered as <input type="email" />.
May be this will be helpful for someone. Following works for me
[Required(ErrorMessage = "*")]
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string Email { get; set; }
But does not work following
[Required(ErrorMessage = "*")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
I am using MVC 5 & .NET 4.5
As Felix mentioned, the problem is on the View level, you need to use EditorFor() in your View instead of TextBoxFor(), the EditorFor() will render:
<input type="email" />
which will trigger the validation, while TextBoxFor() will render:
<input type="text" />
So in order to validate your entered email address, you need (in combination with EditorFor()) to use only:
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
This way, your entered value for email will be always validated, but if you don't enter a value for email, nothing will happen (unless you specified the [Required] attribute), the form will be submitted with an empty email address.
[DataType(DataType.EmailAddress)] can't recognize # and [EmailAddress] can't recognize .com , so use RegularExpression :
[RegularExpression(#"^[A-Za-z0-9](([_\.\-]?[a-zA-Z0-9]+)*)#([A-Za-z0-9]+)(([\.\-‌​]?[a-zA-Z0-9]+)*)\.([A-Za-z]{2,})$", ErrorMessage = "Email is not valid")]

How do attributes work in MVC2

I'm trying to work out exactly what role the attributes play when used on model properties.
For example, If I have a Customer model with a display name attribute set on one of the properties, then I can access the display name attribute value within a display template for whatever reason.
public class Customer {
[DisplayName("Customer Name")]
public string Name { get; set; }
}
/Shared/DisplayTemplates/String.ascx <--- Uses this
<p><%=Model %> | <%=ViewData.ModelMetadata.DisplayName %></p>
-
If however I change the DisplayName attribute to DataType, then MVC looks for a template also called ImageUrl.
public class Customer {
[DataType(DataType.ImageUrl)]
public string Name { get; set; }
}
/Shared/DisplayTemplates/ImageUrl.ascx <---Uses this
<img href="<%=Model %>" /> | <%=ViewData.ModelMetadata.DisplayName %>
Why is the String template being ignored? I thought that MVC matches up the datatypes of the properties to the template names (like the first example) and the attributes are used as metadata within the templates.
It's all very confusing!
MVC matches the datatype of the property when looking for a template - as in your first example.
In your second example, your [DataType] attribute has overriden the string definition, so it now looks for a template named the same as the data type.
If you want to specify which template a property will use you can use the UIHint attribute
public class Customer {
[UIHint("string")]
[DataType(DataType.ImageUrl)]
public string Name { get; set; }
}

Does the Model Binder in ASP.NET MVC Beta Support List<T>?

Take the example classes below. I want to display the customer and two addresses (from a LIST) on a form. Does the model binder in MVC beta support this or will I have to write my own custom binder?
public class Customer
{
public string FirstName { get; set; }
public string LastName { get; set; }
public List<Address> Addresses { get; set; }
public Customer()
{
Addresses = new List<Address>();
}
}
public class Address
{
public int Line1 { get; set; }
public int Line2 { get; set; }
public int City { get; set; }
public int State { get; set; }
public int Zip { get; set; }
}
How would you code the fields? Like this?
<!-- some HTML formatting -->
<%= Html.TextBox("customer.address.line1", ViewData.Customer.Address[0].Line1)%>
<!-- some more HTML formatting -->
<%= Html.TextBox("customer.address.line1", ViewData.Customer.Address[1].Line1)%>
<!-- end of HTML form formatting -->
I've never tried it, but see this post, it's about model binding to a list, maybe it can help you.
Use MvcContrib's NameValueDeserializer to make it simpler. Let's assume that your page derives from ViewPage<Customer>. You can do this:
<%= Html.TextBox("Address[0].Line1", ViewData.Model.Address[0].Line1)%>
<%= Html.TextBox("Address[1].Line1", ViewData.Model.Address[1].Line1)%>
And this:
public ActionResult Save([Deserialize]Customer customer)
And the customer will be deserialized from the form post with the address collection populated. Your indexes do not have to be in sequence -- this supports cases where you want to remove rows on the client side before the post occurs.
In the case that you are deserializing something from the view data dictionary (instead of the Model), then the syntax is like [Deserialize("customer")], where "customer" is the prefix.
You might find this blog post interesting and relevant.
Just to make this complete. It's important that you use the hidden fields with the name Index. So my code above becomes this:
<!-- some HTML formatting -->
<%= Html.Hidden("customer.address.Index", 0) %>
<%= Html.TextBox("customer.address[0].line1", ViewData.Customer.Address[0].Line1)%>
<!-- some more HTML formatting -->
<%= Html.Hidden("customer.address.Index", 1) %>
<%= Html.TextBox("customer.address[1].line1", ViewData.Customer.Address[1].Line1)%>
<!-- end of HTML form formatting -->
It works like a charm!
You can pass an object list with ViewData like that, but you need to change some of the lines. Read more here:
http://weblogs.asp.net/scottgu/archive/2007/12/06/asp-net-mvc-framework-part-3-passing-viewdata-from-controllers-to-views.aspx
and here:
ASP.NET MVC: How do I pass a list (from a class in Model) to a repeater in a View?
Hope this helps
Edit
If you use a model, you need to set up the DataContext first and select the list, but sure you can use the classes generated if you use LINQ.
I defined a similar object. I followed the post on binding to a list as referenced above, While the binding works,I was unable to use the Bind whitelist or blacklist in the controller's action parameter. THe model is an IList

Resources