How are you meant to use Prompt, Description, Ordering when applying data-annotations in ASP.NET MVC 3 - asp.net-mvc-3

I have a view model with a property on it that looks like this:
[Display(Name = "Some Property", Description = "This is description", Prompt = "This is prompt")]
[Required(ErrorMessage = RequiredFieldMessage)]
public string SomeProperty { get; set; }
But this does not seem to render anything extra in the view. Do you need to do some additional work?
<div class="editor-label">
#Html.LabelFor(model => model.SomeProperty )
</div>
<div class="editor-field">
#Html.TextAreaFor(model => model.SomeProperty , 5, 80, null)
#Html.ValidationMessageFor(model => model.SomeProperty )
</div>

Not all of the built in EditorTemplates take advantage of all of the DataAnnotations, but they are there for when you write your own EditorTemplates you can leverage them.
Ordering doesn't really apply unless you are doing DisplayForModel or EditorForModel where its showing multiple editors for all the properties on the model, it can then order the Editor's appropriately.
If you wanted to take advantage of the Description and Prompt metadata you could write your own String EditorTemplate:
#model string
#Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new {
#title = ViewData.ModelMetadata.Description,
#placeholder = ViewData.ModelMetadata.Watermark})

Related

MVC 5 Conditional Validation Option?

I'm developing an MVC 5 web application. Within a particular View I need to validate a ViewModel, however, I need some of the validation only to occur depending on the users inpupt.
For example, I have a ViewModel
public class TimeEntryViewModel
{
public int proposalID { get; set; }
public int proposalCode { get; set; }
public int nonchargeCode { get; set; }
public SelectList UserProposals { get; set; }
public SelectList TimeEntryClientCodes { get; set; }
public SelectList TimeEntryNonChargeCodes { get; set; }
}
This ViewModel is passed to a View which looks like this
<div class="form-group">
#Html.LabelFor(m => m.proposalID, "Proposal")
#Html.DropDownListFor(m => m.proposalID, Model.UserProposals, "No Proposal", new { #class = "form-control"})
#Html.ValidationMessageFor(m => m.proposalID)
</div>
<div id="ClientCodes" class="form-group" style="display:none">
#Html.LabelFor(m => m.proposalCode, "Client")
#Html.DropDownListFor(m => m.proposalCode, Model.TimeEntryClientCodes, "Select", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.proposalCode)
</div>
<div id="NonChargeCodes" class="form-group">
#Html.LabelFor(m => m.nonchargeCode, "Non Charge")
#Html.DropDownListFor(m => m.nonchargeCode, Model.TimeEntryNonChargeCodes, "Select", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.nonchargeCode)
</div>
If the user selects 'No Proposal' from the first drop down list, then the drop down list 'nonchargeCode' appears and I need to validate so that the user selects an option from it.
However, if the user selects another option from the first down drop list, then the drop down list 'nonchargeCode' will disappear and another drop down called 'proposalCode' will appear. I then want to validate to ensure the user selects an option from this drop down, but not the 'nonchargeCode' (which will be hidden).
In an MVC 4 application I previously coded, I used http://fluentvalidation.codeplex.com/ to help with this scenario.
I'm just wondering if anyone else had used anything else to overcome this problem of conditional validation? If so, I'd be keen to hear.
Thanks again.
You can use conditional validation in jQuery and in fluentvalidation.
You can use a jQuery selector on the validation, something like this.
I'm not sure about the HTML element names.
$( "#myform" ).validate({ rules: {
proposalCode: {
required: "#proposalCode:visible"
} }
Check out jQuery Dependency expression for more information.
In FluentValidation validation (Server side only) you can use the 'When' expression.
RuleFor(r => r.proposalCode).NotNull().When(e => // Check selected value);
Check out the documentation here
I think this should get you started.

How to keep the same data when return to the view?

How to keep the same data when return to the view?
I tried to put return the form to the view, but it did not work.
Is there any good and simple way to do this?
[HttpPost]
public ActionResult Register(FormCollection form)
{
string name = form["Name"].Trim();
if (string.IsNullOrEmpty(name))
{
TempData["TempData"] = "Please provide your name ";
return View(form);
}
string email = form["Email"].Trim();
var isEmail = Regex.IsMatch(email, #"(\w+)#(\w+)\.(\w+)");
if (!isEmail)
{
TempData["TempData"] = "Sorry, your email is not correct.";
return View(form);
}
//do some things
}
Not sure why you would be using FormCollection in the post but maybe you come from a WebForms background. In MVC you should use ViewModels for the transport of your data to and from the Views.
By default the Register method in an MVC 3 app uses a ViewModel in the Register View. You should simply post it back. In fact, the default app has that already created for you if you didn't know as part of the Internet template.
The standard pattern is to have a ViewModel that represents your data that you will use in your View. For example, in your case:
public class RegisterViewModel {
[Required]
public string Name { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
}
Your controller the should contain 2 actions, a Get and a Post. The Get renders the View and is ready for the user to enter data. upon submitting the View the Post action is then called. The View sends the ViewModel to the action and the method then takes action to validate and save the data.
If there is a validation error with the data, it's very simple to return the ViewModel back to the View and display the error messages.
Here is the Get action:
public ActionResult Register() {
var model = new RegisterViewModel();
return View(model);
}
And here is the Post action:
[HttpPost]
public ActionResult Register(RegisterViewModel model) {
if(ModelState.IsValid) { // this validates the data, if something was required, etc...
// save the data here
}
return View(model); // else, if the model had validation errors, this will re-render the same view with the original data
}
Your view would look something like this
#model RegisterViewModel
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Name) <br />
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
#Html.TextBoxFor(model => model.Email) <br />
#Html.ValidationMessageFor(model => model.Email)
</div>
}
Using other strategies to capture and save data in an MVC app is absolutely possible, it's a very extensible framework. But there is a specific pattern that makes MVC what it is and working against that pattern can sometimes prove difficult. For a beginner it is best to understand the preferred patterns and strategies first and then once understood very well, you can then adopt some of your own custom strategies to meet your needs. By then you should understand the system well enough to know what you need to change and where.
Happy coding!!

Validation of DropDownListFor is not working in MVC3?

Validation is Working on Other Input type text element but not working on DropDownListFor
Class Purchase Input Property Code
[Required]
public string LedgerId { get; set; }
Class View Model Code
PurchaseViewModel purchaseVM = new PurchaseViewModel
{
// PurchaseInput=purchaseInput,
Ledger = uw.LedgerRepository.Get().Select(x => new SelectListItem { Value = x.Id.ToString(), Text = x.LedgerName }),
};
View
<div class="column">
<div class="labelField">
#Html.LabelFor(model => model.PurchaseInput.LedgerId, "Party")
</div>
<div class="ItemField">
#Html.DropDownListFor(model => model.PurchaseInput.LedgerId, new SelectList(Model.Ledger, "Value", "Text"))
#Html.ValidationMessageFor(model => model.PurchaseInput.LedgerId)
</div>
</div>
On the face of it, it seems that you do not have an empty item in your select list. The validation will only trigger if the user selects a dropdown item with string length of zero. If you examine the Html source can you see the validation attributes on the dropdown ( depending on whether you are using unobtrusive validation or not)?
Yes, there are problems with validation of DropDownListFor. look at this link. They get validation data manually from metadata - http://forums.asp.net/t/1649193.aspx
Although this is a workaround, at least it fires some sort of validation. Try:
#Html.DropDownListFor(model => model.PurchaseInput.LedgerId, new SelectList(Model.Ledger, "Value", "Text"), new { #class = "required" })

MVC3 Navigation Property Attributes and Client Side Validation

I am making my first tentative steps into MVC3 and have come across an issue with the translation of navigation properties within a model to a view. It seems that in the view navigational properties do not allow client side validation nor is the "Display" label attribute picked up.
I have the following simple model:
public class Entity
{
[Key,
ScaffoldColumn(false)]
public int Entity_Id { get; set; }
[Display(Name = "Entity Name"),
Required(ErrorMessage = "Please enter the entity name."),
StringLength(150, ErrorMessage = "Please ensure that the entity name is under 150 characters.")]
public string Entity_Nm { get; set; }
[Display(Name = "Entity Type"),
Required(ErrorMessage="Please select the entity type"),
ForeignKey("EntityType")]
public int EntityType_Id { get; set; }
public virtual EntityType EntityType { get; set; }
}
Which references this model:
public class EntityType
{
[Key]
public int EntityType_Id { get; set; }
[Display(Name = "Entity Name"), Required(ErrorMessage="Please enter the entity type name.")]
public string EntityType_Nm { get; set; }
}
When I create a controller with read/write actions and views for this model I get the following create form:
<fieldset>
<legend>Entity</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Entity_Nm)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Entity_Nm)
#Html.ValidationMessageFor(model => model.Entity_Nm)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.EntityType_Id, "EntityType")
</div>
<div class="editor-field">
#Html.DropDownList("EntityType_Id", String.Empty)
#Html.ValidationMessageFor(model => model.EntityType_Id)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
This is fine apart from the label for the Entity Type drop down, for some reason it is not picking up the "Display" attribute of the navigation property within the model (note the lack of a space). Also client side validation is not enabled for the dropdown list (server side validation works without issue) despite decorating the property with a "Required" attribute. Client side validation works on the other fields. Please note that all the required .js script files have been included and I have also added the relevant enable validation keys to the web.config.
Any ideas what I am missing here? Thanks one and all.
for DropDownList Display issue just try below
#Html.LabelFor(model => model.EntityType_Id)

Dropdown list filled from repository

I have an MVC3 drop down list that come from this code on the controller.
private SelectList progCodesList = new SelectList(new[] { "Description", "Requirements", "Development", "Testing", "Documentation" });
How can I fill the fields from a repository, to build the drop down dynamically?
Thanks.
Assuming you have the progCodes in a database table, with progCode having the text, and progCodeId with a unique id, then you can read the table into a list of SelectListItem as follows:
private DbContext _db = new DbContext();
var progCodesList = _db.progCodes.Select(x => new SelectListIem()
{
Text = x.progCode,
value = x.progCodeId
}).ToList();
You can then pass this List<SelectListItem> to your view either in a strongly-typed model, or using the ViewBag.
You need to pass the progCodesList to the ViewBag in your controller method using something like:
ViewBag.ProgCodeId = progCodesList;
Then in your view, you need to fill the drop down like this:
<div class="editor-label">
#Html.LabelFor(model => model.ProgCodeId, "ProgCode")
</div>
<div class="editor-field">
#Html.DropDownList("ProgCodeId", String.Empty)
#Html.ValidationMessageFor(model => model.ProgCodeId)
</div>

Resources