Required message for Unmapped field? - asp.net-mvc-3

I have an unmapped field in asp.net MVC3. I want to display required message for this field but i can't. How can i display required messsage for unmapped fields? Is it possible ?
[Required(ErrorMessage = "Email alanı girilmelidir.")]
public string FirstEMail
{
get
{
return first_email;
}
set
{
first_email = value;
}
}
DAL:
modelBuilder.Entity<AbsKontak>().Ignore(p => p.FirstEMail);
View:
Html.LabelFor(p => p.FirstEMail)
Html.TextBoxFor(p => p.FirstEMail, new { class = "medium", disabled = "disabled", id = "txtFirstTel" })
Html.ValidationMessageFor(p => p.FirstEMail)

Is this your requirement, Please let me know if Iam wrong
Model:
[Required(ErrorMessage="FirstEMail is required")]
public string FirstEMail{get;set;}
Controller:
public ActionResult ValidatingFormMessages()
{
UserEmail objModel = new UserEmail();
objModel.FirstEMail = "xxx#yy.com";
return View(objModel);
}
[HttpPost]
public ActionResult Index(UserEmail coll)
{
if (ModelState.IsValid)
{
return RedirectToAction("yourActionName", "YourControllerName");
}
return View();
}
View:
#{Html.BeginForm();}
#Html.TextBoxFor(x => x.FirstEMail)
#Html.ValidationMessageFor(x => x.FirstEMail)
<input type="submit" id="btnSubmit" value="Submit" />
#{Html.EndForm();}

Related

validate dropdown in mvc5

I am having trouble in attempting to validate that a value has been chosen from a dropdown as follows:
Please Select Type
Keypad
Bill Pay
I have added the following details as part of my model:
[Required]
[StringLength(20, MinimumLength = 10)]
public string AccountType { get; set; }
When I post the form it is not highlighting the account type as not being filled out correctly. Any ideas why? I thought that the minimum length would have caught this
I will show validation for country below.
Model:
public class CountryModel
{
[Required(ErrorMessage="Country Required.")]
public int SelectedCountryId { get; set; }
public System.Web.Mvc.SelectList Countries { get; set; }
}
Controller:
public ActionResult Index(CountryModel model)
{
if (model.Countries == null)
{
model.Countries = new SelectList(new List<SelectListItem>()
{
new SelectListItem() { Text= "India", Value = "1" },
new SelectListItem() { Text= "Australia", Value = "2"}
},"Value","Text");
}
return View(model);
}
My View:
#model MVCControls.Models.CountryModel
#{
ViewBag.Title = "Index";
}
<h2>Dropdownlist Validation</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary()
#Html.Label("Country")
#Html.DropDownListFor(c => c.SelectedCountryId,Model.Countries, "..Select..")
#Html.ValidationMessage("Country is required.");
<input type="submit" name="name" value="Submit" />
}
Hope this helps

Asp.net MVC3 custom validator created using dataannotation showing messages in incorrect place

I am using Asp.net MVC3, razor view engine and data annotation for model validation.
I have a form in which have to input Url details(Url and Description).Both fields are not required. But if i input one field other must be required.If i input description Url is required and is in correct format and if i enter Url then description is required.
I created a customvalidator for data annotation .It validates and output error message.
But my problem is error message generated by ValidationMessageFor is in incorrect place.
ie,if i enter description ,the required url message, is part of description.
I expect that message as part of ValidationMessageFor url field.
Can any one can help me? Thanks in advance. Folowing are the code i used
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public sealed class IsExistAttribute : ValidationAttribute, IClientValidatable
{
private const string DefaultErrorMessage = "{0} is required.";
public string OtherProperty { get; private set; }
public IsExistAttribute (string otherProperty)
: base(DefaultErrorMessage)
{
if (string.IsNullOrEmpty(otherProperty))
{
throw new ArgumentNullException("otherProperty");
}
OtherProperty = otherProperty;
}
public override string FormatErrorMessage(string name)
{
return string.Format(ErrorMessageString, name, OtherProperty);
}
protected override ValidationResult IsValid(object value,ValidationContext validationContext)
{
if (value != null)
{
var otherProperty = validationContext.ObjectInstance.GetType()
.GetProperty(OtherProperty);
var otherPropertyValue = otherProperty
.GetValue(validationContext.ObjectInstance, null);
var strvalue=Convert.ToString(otherPropertyValue)
if (string.IsNullOrEmpty(strvalue))
{
//return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName),new[] { OtherProperty});
}
}
return ValidationResult.Success;
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata,ControllerContext context)
{
var clientValidationRule = new ModelClientValidationRule()
{
ErrorMessage = FormatErrorMessage(metadata.GetDisplayName()),
ValidationType = "isexist"
};
clientValidationRule.ValidationParameters.Add("otherproperty", OtherProperty);
return new[] { clientValidationRule };
}
}
in model
[Display(Name = "Description")]
[IsExist("Url")]
public string Description { get; set; }
[Display(Name = "Url")]
[IsExist("Description")]
[RegularExpression("(http(s)?://)?([\w-]+\.)+[\w-]+(/[\w- ;,./?%&=]*)?", ErrorMessage = "Invalid Url")]
public string Url { get; set; }
and in view
<div class="editor-field">
#Html.TextBoxFor(m => m.Description )
#Html.ValidationMessageFor(m => m.Description)
</div>
<div class="editor-field">
#Html.TextBoxFor(m => m.Url)
#Html.ValidationMessageFor(m => m.Url)
</div>
unobstrusive validation logic
(function ($) {
$.validator.addMethod("isexist", function (value, element, params) {
if (!this.optional(element)) {
var otherProp = $('#' + params)
return (otherProp.val() !='' && value!='');//validation logic--edited by Rajesh
}
return true;
});
$.validator.unobtrusive.adapters.addSingleVal("isexist", "otherproperty");
} (jQuery));
You should make the validation the other way round. Change:
if (string.IsNullOrEmpty(otherPropertyValue))
{
//return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName),new[] { OtherProperty});
}
To:
if (string.IsNullOrEmpty(Convert.ToString(value)) && !string.IsNullOrEmpty(otherPropertyValue))
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
And remove if (value != null)
The field that will then get invalidated is the empty one, in the case the other one is filled.

Multiple roles in Asp.net MVC3

I have an admin site for the admin to create users. Here he has to chose the roles for the user - like the Asp.NET configuration site. I made 3 checkboxes with different roles.
[Authorize(Roles = "Admin")]
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
var Rolemodel = model.RolesContainer;
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
[Authorize(Roles = "Admin")]
public ActionResult Register()
{
List<SelectListItem> tempRoles = new List<SelectListItem>();
tempRoles.Add(new SelectListItem{ Text = "Admin", Selected = false, Value = "Admin" });
tempRoles.Add(new SelectListItem{ Text = "Production", Selected = false, Value = "Production"});
tempRoles.Add(new SelectListItem{ Text = "Sale", Selected = false, Value = "Sale"});
return View(new RegisterModel { RolesContainer = tempRoles });
}
----View--------
#{ foreach (var item in Model.RolesContainer)
{
#Html.DisplayFor(m => item.Text)
#Html.CheckBoxFor(m => item.Selected)
}
}
When I check them and submit, I get to the breakpoint in my Register action, but the RolesContainer is null at this point - can anyone tell me why this is?
I copied and pasted your code (except the cshtml) into the following files and it works as expected.
HomeController.cs
using System.Collections.Generic;
using System.Web.Mvc;
using MvcApplication1.Models;
namespace MvcApplication1.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
List<SelectListItem> tempRoles = new List<SelectListItem>();
tempRoles.Add(new SelectListItem { Text = "Admin",
Selected = false,
Value = "Admin" });
tempRoles.Add(new SelectListItem { Text = "Production",
Selected = false,
Value = "Production" });
tempRoles.Add(new SelectListItem { Text = "Sale",
Selected = false,
Value = "Sale" });
return View(new RegisterModel { RolesContainer = tempRoles });
}
}
}
RegisterModel
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
namespace MvcApplication1.Models
{
public class RegisterModel
{
[Required]
[Display(Name = "Brugernavn")]
public string UserName { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email adresse")]
public string Email { get; set; }
public List<SelectListItem> RolesContainer { get; set;}
}
}
Home/Index.cshtml
#model MvcApplication1.Models.RegisterModel
#{
foreach (var item in Model.RolesContainer)
{
#Html.DisplayFor(m => item.Text)
#Html.CheckBoxFor(m => item.Selected)
}
}
Most likely there is something wrong in your Register.cshtml file, of which we don't have to validate.
Currently when you are assigning the value to RolesContainer it has not been initialised. You simply need to initialise it in the constructor of your class:
public class RegisterModel
{
public RegisterModel() {
RolesContainer = new List<SelectListItem>;
}
// rest of your code
}
Alternatively you could create a constructor which accepts the List<> as a parameter, but the above method will work for your current code structure.
If I understand well (may be I'm totally wrong), the model you post to httppost register (RegisterModel) doesn't contains the RolesContainer you expect. I think, asp.net mvc is not able to match multiple checkboxes with a List<SelectListItem>, a ListBox should be better

how to get label value in mvc 3?

In Model:
public class DataViewModel
{
public IList<RowsCollection> Rows { get; set; }
public PaiementMethod PaiementMethod { get; set; }
}
public class RowsCollection
{
public string ID { get; set; }
public string Question { get; set; }
}
public enum PaiementMethod
{
Cash,
CreditCard,
}
In the Controller - Index ActionResult I have return my Model and render its into view page something like :
#model WebNexpo.Controllers.DataViewModel
#using (Html.BeginForm("Save", "page", FormMethod.Post, new { id = "saves"}))
{
foreach (var item in Model.Rows)
{
#Html.Label(item.Question)
<label for="paiement_cash">
Cash</label>
#Html.RadioButtonFor(m => m.PaiementMethod, "Cash", new { name = "paiement_cash" + #item.ID + "", id = "radioID" + #item.ID + "", Group = "Group" + #item.ID + "" })
<label for="paiement_cc">
Credit card</label>
#Html.RadioButtonFor(m => m.PaiementMethod, "CreditCard", new { name = "paiement_cc" + #item.ID + "", id = "radioname" + #item.ID + "", Group = "Group" + #item.ID + "" })
}
<input id="Saveser" type="submit" value="" class="button1" />
}
in submit form Action Event :
[HttpPost]
public ActionResult Save(DataViewModel model)
{
if (ModelState.IsValid)
{
//want to read all the label which selected rediobutton.
means suppose 4 question render on page and user have selected only 2
question of the answer.so How can accomplish here?
}
return RedirectToAction("Index", new {value = "123"});
}
There's some inconsistency here. You are rendering 2 radio buttons for each row so you probably want to reorganize your view model into:
public class DataViewModel
{
public IList<RowsCollection> Rows { get; set; }
}
public class RowsCollection
{
public string ID { get; set; }
public string Question { get; set; }
public PaiementMethod PaiementMethod { get; set; }
}
and then:
#model DataViewModel
#using (Html.BeginForm("Save", "page", FormMethod.Post, new { id = "saves"}))
{
for (var i = 0; i < Model.Rows.Count; i++)
{
<div>
#Html.HiddenFor(x => x.Rows[i].ID)
#Html.LabelFor(x => x.Rows[i].Question)
#Html.EditorFor(x => x.Rows[i].Question)
#Html.Label("payment_cash" + i, "Cash")
#Html.RadioButtonFor(m => m.Rows[i].PaiementMethod, "Cash", new { id = "payment_cash" + i })
#Html.Label("payment_cc" + i, "Credit card")
#Html.RadioButtonFor(m => m.Rows[i].PaiementMethod, "CreditCard", new { id = "payment_cc" + i })
</div>
}
<input id="Saveser" type="submit" value="" class="button1" />
}
and finally:
[HttpPost]
public ActionResult Save(DataViewModel model)
{
if (ModelState.IsValid)
{
// model.Rows[0].PaiementMethod will contain the selected payment method for the first question
// model.Rows[1].PaiementMethod will contain the selected payment method for the second question
// ...
}
return RedirectToAction("Index", new { value = "123" });
}
or if you want a single payment method you could keep your view model as is but then leave the radio buttons outside of the loop in your view. Like that:
#using (Html.BeginForm("Save", "page", FormMethod.Post, new { id = "saves" }))
{
for (var i = 0; i < Model.Rows.Count; i++)
{
<div>
#Html.HiddenFor(x => x.Rows[i].ID)
#Html.LabelFor(x => x.Rows[i].Question)
#Html.EditorFor(x => x.Rows[i].Question)
</div>
}
#Html.Label("payment_cash", "Cash")
#Html.RadioButtonFor(x => x.PaiementMethod, "Cash", new { id = "payment_cash" })
#Html.Label("payment_cc", "Credit card")
#Html.RadioButtonFor(x => x.PaiementMethod, "CreditCard", new { id = "payment_cc" })
<input id="Saveser" type="submit" value="" class="button1" />
}

drop down list validation message mvc

In my viewModel I have
public string Addressline1 { get; set; }
public List<SelectListItem> StateList
{
get
{
return State.GetAllStates().Select(state => new SelectListItem { Selected = false, Text = state.Value, Value = state.Value }).ToList();
}
}
In the view I have
#Html.DropDownListFor(model => model.StateCode, Model.StateList, "select")
when AddressLine1 is entered, then the statelist DropDownList selection is Required.How do I validate and show an error message when no state is selected in the Drop down list other than default "select" value?
Decorate your StateCode property with the [Required] attribute:
[Required(ErrorMessage = "Please select a state")]
public string StateCode { get; set; }
public IEnumerable<SelectListItem> StateList
{
get
{
return State
.GetAllStates()
.Select(state => new SelectListItem
{
Text = state.Value,
Value = state.Value
})
.ToList();
}
}
and then you could add a corresponding validation error message:
#Html.DropDownListFor(model => model.StateCode, Model.StateList, "select")
#Html.ValidationMessageFor(model => model.StateCode)
UPDATE:
Alright it seems that you want to conditionally validate this StateCode property depending on some other property on your view model. Now that's an entirely different story and you should have explained this in your original question. Anyway, one possibility is to write a custom validation attribute:
public class RequiredIfPropertyNotEmptyAttribute : ValidationAttribute
{
public string OtherProperty { get; private set; }
public RequiredIfPropertyNotEmptyAttribute(string otherProperty)
{
if (otherProperty == null)
{
throw new ArgumentNullException("otherProperty");
}
OtherProperty = otherProperty;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var property = validationContext.ObjectType.GetProperty(OtherProperty);
if (property == null)
{
return new ValidationResult(string.Format(CultureInfo.CurrentCulture, "{0} is an unknown property", new object[]
{
OtherProperty
}));
}
var otherPropertyValue = property.GetValue(validationContext.ObjectInstance, null) as string;
if (string.IsNullOrEmpty(otherPropertyValue))
{
return null;
}
if (string.IsNullOrEmpty(value as string))
{
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
}
and now decorate your StateCode property with this attribute, like so:
public string AddressLine1 { get; set; }
[RequiredIfPropertyNotEmpty("AddressLine1", ErrorMessage = "Please select a state")]
public string StateCode { get; set; }
Now assuming you have the following form:
#using (Html.BeginForm())
{
<div>
#Html.LabelFor(x => x.AddressLine1)
#Html.EditorFor(x => x.AddressLine1)
</div>
<div>
#Html.LabelFor(x => x.StateCode)
#Html.DropDownListFor(x => x.StateCode, Model.States, "-- state --")
#Html.ValidationMessageFor(x => x.StateCode)
</div>
<input type="submit" value="OK" />
}
the StateCode dropdown will be required only if the user entered a value into the AddressLine1 field.

Resources