MVC Razor retrieve Description text from Model in HTML helper class - asp.net-mvc

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})

Related

asp.net mvc client side validation using jQuery

Does asp.net mvc client side validation using jQuery only work with views
which use HTML Helpers to generate HTML controls? Does it work with standard HTML Controls?
It is possible to use validation without turning to HtmlHelpers. See this article for details about how MVC works in the background with unobtrusive validation.
http://www.blinkingcaret.com/2016/03/23/manually-use-mvc-client-side-validation/
Though I think unless you have a very specific requirement, rather stick with Helpers, it will make your life easier.
1)Add Validation Property in model
2)In view add html control for show the validation
1)For Model
[Required(ErrorMessage = "Name is Required")]
public string Name { get; set; }
[Required(ErrorMessage = "Email is Required")]
[EmailAddress(ErrorMessage = "Invalid Email Address")]
public string Email { get; set; }
2)In View
#Html.TextBoxFor(m => m.Email)
#Html.ValidationMessageFor(m => m.Email, "", new { #class = "error" })
3)Most Important (Add the following link in the View Page)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-
validate/1.19.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-
unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>

MVC EditorFor only rendering single property, not EditorTemplate

Got some issues with EditorFor and I can't understand the behaviour.
I have a list of objects where I want to render an editor template based on that list.
According to https://stackoverflow.com/a/26069912 the EditorFor should render the template for each object.
public class Person
{
public string Name { get; set; }
public string PhoneNumber { get; set; }
}
The template
#model EditForTest.Models.Person
Name
<td>#Html.TextBoxFor(x => x.Name)</td>
Phone
<td>#Html.TextBoxFor(x => x.PhoneNumber)</td>
In the view I got a view model containing a list of persons. When I use
#Html.EditorFor(x => x.Persons)
the template is not rendered and somehow the first property is rendered on the page.
As #StephenMuecke mentioned I had a problem with my editor template.
Once the template was moved to the correct path /Views/Shared/EditorTemplates/Person.cshtml the editor was rendered properly.

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

Can I use more than one editor template for the same class in MVC3?

I have for example a class:
public class Book
{
public int BookId { get; set; }
public string BookName { get; set; }
public string Description { get; set; }
}
and an editor template:
#model MySimpleEditorTemplate.Models.Book
#Html.DisplayFor(p => p.BookId) #Html.EditorFor(p => p.BookId)
#Html.DisplayFor(p => p.BookName) #Html.EditorFor(p => p.BookName)
#Html.DisplayFor(p => p.Description) #Html.EditorFor(p => p.Description)
I can use the editor template like this:
#Html.EditorFor(model => model.Book)
However what if I want to have two editor templates or two display templates and use one or other for the same class? Is this possible?
YES, you can have the "default" one, with its name Book.cshtml... and this one is triggered every time you use EditorFor.
You can have another editor template for Book, let's say calling it BookTheOtherWay.cshtml and there you place your "other editor view". Now, when using EditorFor, you just need to pass the template name as other parameter in the EditorFor template.
#Html.EditorFor(model => model.MyBook, "BookTheOtherWay" )
This works the same way for DisplayTemplates and the DisplayFor helper.
#Html.DisplayFor(model => model.MyBook, "BookTheOtherWay" )
Yes
public static MvcHtmlString EditorFor<TModel, TValue>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression,
string templateName
)
http://msdn.microsoft.com/en-us/library/ff406506.aspx
"If a template whose name matches the templateName parameter is found in the controller's EditorTemplates folder, that template is used to render the expression. If a template is not found in the controller's EditorTemplates folder, the Views\Shared\EditorTemplates folder is searched for a template that matches the name of the templateName parameter. If no template is found, the default template is used."

Trouble getting DropDownListFor to work on EditorFor in MVC3

I've got a pretty simple problem that has a solution I'm not able to find.
Given the following model:
public class InfoViewModel
{
public SelectList States { get; set; }
[DisplayName("State")]
public string State { get; set; }
}
The following works fine in my view:
#Html.DropDownListFor(m => m.State, Model.States)
However, if I try to pull this into an editor template (named "SelectList"), such as:
#model System.String
#Html.DropDownListFor(m => m, ViewData["selectList"])
And then use EditorFor to build the dropdown list:
#Html.EditorFor(m => m.State, "SelectList", new { selectList = Model.States })
It fails with the following error:
'System.Web.Mvc.HtmlHelper<string>' does not contain a definition for
'DropDownListFor' and the best extension method overload
'System.Web.Mvc.Html.SelectExtensions.DropDownListFor<TModel,TProperty>
(System.Web.Mvc.HtmlHelper<TModel>,
System.Linq.Expressions.Expression<System.Func<TModel,TProperty>>,
System.Collections.Generic.IEnumerable<System.Web.Mvc.SelectListItem>)'
has some invalid arguments
I'm having a hard time understanding the difference between these two. I've tried various workarounds to troubleshoot, and either get the same error, or something else.
Thanks in advance.
There is no such overload:
#Html.DropDownListFor(m => m, ViewData["selectList"])
The second parameter of the DropDownListFor helper musty be a SelectList. So:
#Html.DropDownListFor(m => m, (SelectList)ViewData["selectList"])

Resources