SelectListItem properties in view model are not passed back from view to controller - asp.net-mvc

I have this View Model:
public class UserViewModel
{
public string ID { get; set; }
[Required]
[Display(Name = "Nombre")]
public string Nombre { get; set; }
[Required]
[Display(Name = "Login")]
public string Login { get; set; }
[Required]
[DataType(DataType.Password)]
[Display(Name = "Contraseña")]
public string Password { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "E-mail")]
public string Email { get; set; }
[DataType(DataType.PhoneNumber)]
[Display(Name = "Teléfono")]
public string PhoneNumber { get; set; }
[Display(Name = "Ciudad")]
public System.Web.Mvc.SelectListItem City { get; set; }
[Display(Name = "Empresas")]
public IEnumerable<System.Web.Mvc.SelectListItem> Empresas { get; set; }
[Required]
[Display(Name = "Perfil")]
public string Role { get; set; }
[Display(Name = "Está Vigente")]
public bool Vigente { get; set; }
}
the problem I am having is that when I select something in City and Empresas in the form (they are both SELECT fields), they are not passed to controller in UserViewModel parameter:
public JsonResult EditUser(UserViewModel model)
{
.....
}
Only other properties are passed.
What is the right way to manage this?
EDIT:
this is part of the view:
#using (Html.BeginForm("EditUser", "Account", new { area = "Security" }, FormMethod.Post, new { #class = "form-horizontal form-label-left", role = "form", novalidate = "novalidate", id = "frmUsuario" }))
{
var id = Model == null ? String.Empty : Model.ID;
<div class="errores col-md-12 col-sm-12 col-xs-12" style="display: none">
<div class='validation-summary-errors alert alert-danger alert-white rounded' data-valmsg-summary="true">
<div class="icon">
<i class="fa fa-times-circle"></i>
</div>
<p>Debe completar los campos marcados en forma correcta.</p>
</div>
</div>
#Html.AntiForgeryToken();
<input type="hidden" value="#id" id="id" name="id" />
<div class="item col-md-12 col-sm-12 col-xs-12 form-group has-feedback">
#Html.TextBoxFor(m => m.Nombre, new { #class = "form-control has-feedback-left", placeholder = "Nombre", required = "required" })
<span class="fa fa-user form-control-feedback left" aria-hidden="true"></span>
</div>
<div class="item col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
#Html.TextBoxFor(m => m.Login, new { #class = "form-control has-feedback-left", placeholder = "Login", required = "required" })
<span class="fa fa-sign-in form-control-feedback left" aria-hidden="true"></span>
</div>
<div class="item col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
#{
//var requerido = String.IsNullOrEmpty(userId) ? "required" : String.Empty;
var requerido = Model == null || String.IsNullOrEmpty(Model.ID);
object htmlAttributes = null;
if (requerido)
{
htmlAttributes = new { #class = "form-control has-feedback-left", placeholder = "Contraseña", required = "required" };
}
else
{
htmlAttributes = new { #class = "form-control has-feedback-left", placeholder = "Contraseña" };
}
}
<!-- Para evitar que los password managers llenen los campos -->
<input type="text" id="hidUser" style="display: none" />
<!-- Para evitar que los password managers llenen los campos -->
<input type="password" id="hidPassword" style="display: none" />
#Html.PasswordFor(m => m.Password, htmlAttributes)
<span class="fa fa-key form-control-feedback left" aria-hidden="true"></span>
</div>
<div class="item col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control has-feedback-left", placeholder = "E-mail", required = "required" })
<span class="fa fa-envelope form-control-feedback left" aria-hidden="true"></span>
</div>
<div class="item col-md-6 col-sm-6 col-xs-12 form-group has-feedback">
#Html.TextBoxFor(m => m.PhoneNumber, new { #class = "form-control has-feedback-left", placeholder = "Teléfono" })
<span class="fa fa-phone form-control-feedback left" aria-hidden="true"></span>
</div>
<div class="item col-md-12 col-sm-12 col-xs-12 form-group">
#Html.DropDownListFor(m => m.City, new SelectList(new List<SelectListItem>()), new { style = "width: 100%" })
</div>
<div class="item col-md-12 col-sm-12 col-xs-12 form-group">
#Html.DropDownListFor(m => m.Role, new SelectList(new List<SelectListItem>()), new { style = "width: 100%" })
</div>
<div class="item col-md-12 col-sm-12 col-xs-12 form-group">
#Html.DropDownListFor(m => m.Empresas, new SelectList(new List<SelectListItem>()), new { style = "width: 100%", multiple = "multiple" })
</div>
<div class="item col-md-12 col-sm-12 col-xs-12 form-group">
Está Vigente
#Html.CheckBoxFor(m => m.Vigente, new { #class = "flat" })
</div>
}

Please change the type of City Property in UserViewModal
public string City { get; set; }
Then it will return selected option value to controller for e.g
<select
<option value="1">Delhi </option>
<option value="2">Surat </option>
</select>
if you select Delhi then it will assign value 1 to property

I wonder there's show nothing in your dropdown.
In your view model, it should contain at least two properties, such as AvailableCities and City.
public List<SelectListItem> AvailableCities { get;set; }
public string City { get;set; }
AvailableCities contains all cities which should show in dropdow. And the City is using for getting the value user selected.
In your view,
#Html.DropDownListFor(m => m.City, Model.AvailableCities, new { #class = "form-control" })
For now, you should see the dropdown shawn and which could get the selected value in your action.

Related

summarizing duplicate line items in shopping cart with MVC/EF

I am currently working on creating a simple shopping cart where line items are being displayed based on a call to a table. Primarily I am taking advantage of basic CRUD here, so I am reading a table, filtered out userID and checking whether a orderID has been assigned or not (to avoid redisplaying ordered items in the shopping cart).
All fine, all working, but for esthetic reasons I would like to handle cases where the same product (same ProductID, same ProductName, but i.e. different quantity) is being summarized in one position (order quantity A + order quantity B, etc) rather than having multiple line items with different quantities.
Side note: I am offering subscriptions as well as single orders (differentiated by a Boolean in the table), so please don't let that irritate here.
the Model for LineItems looks as follows:
public class LineItems
{
public int ID { get; set; }
public string UserID { get; set; }
public int ProductID { get; set; }
public string ProductName { get; set; }
//[Range(1, int.MaxValue, ErrorMessage = "Naja... Menge 0 lohnt sich nicht zu liefern...")]
public int SubscriptionQuantity { get; set; }
public string SubscriptionCadenceCategory { get; set; }
public int SubscriptionCadenceValue { get; set; }
public decimal SubscriptionPrice { get; set; }
public bool IsSingleOrder { get; set; }
//[Range(1, int.MaxValue, ErrorMessage = "Naja... Menge 0 lohnt sich nicht zu liefern...")]
public int SingleOrderQuantity { get; set; }
public decimal SingleOrderPrice { get; set; }
public decimal TotalPrice { get; set; }
public int OrderNumber { get; set; }
public DateTime UpdatedTimeStampUTC { get; set; }
public string UpdatedLatitude { get; set; }
public string UpdatedLongitude { get; set; }
public string UpdatedLocation { get; set; }
}
and the View:
<div id="shoppingCart" class="productTableSection row">
#foreach (var item in Model)
{
if (item.IsSingleOrder == false)
{
<div id="shoppingCartSubscriptionLineItemArea" class=" tableArea col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-1 col-md-10 col-lg-offset-2 col-lg-8">
#Html.HiddenFor(modelItem => item.ID, new { #class = "tableField col-xs-12 col-sm-12 col-md-12 col-lg-12" })
<a id="shoppingCartSubscriptionRemoveLink" class="tableField col-xs-1 col-sm-1 col-md-1 col-lg-1" href="#">
<i id="shoppingCartSubscriptionRemove" class="fas fa-trash-alt"></i>
</a>
<a id="shoppingCartSubscriptionLineItemLink" class="tableField col-xs-10 col-sm-10 col-md-10 col-lg-10" href="#Url.Action("ProductSubscription", "freshNclean", new { id = item.ID })">
<div id="shoppingCartSubscriptionProductNameField" class="tableField col-xs-7 col-sm-8 col-md-9 col-lg-9">
#Html.DisplayFor(modelItem => item.ProductName)
</div>
<div id="shoppingCartSubscriptionProductPriceField" class="tableField col-xs-5 col-sm-4 col-md-3 col-lg-3">
CHF #Html.DisplayFor(modelItem => item.SubscriptionPrice)
</div>
<div id="shoppingCartSubscriptionProductQuantityField" class="tableField col-xs-4 col-sm-4 col-md-5 col-lg-5">
#Html.DisplayFor(modelItem => item.SubscriptionQuantity) x
</div>
<div id="shoppingCartSubscriptionCadenceValueField" class="tableField col-xs-3 col-sm-2 col-md-2 col-lg-1">
alle #Html.DisplayFor(modelItem => item.SubscriptionCadenceValue)
</div>
<div id="shoppingCartSubscriptionCadenceCategoryField" class="tableField col-xs-5 col-sm-6 col-md-5 col-lg-6">
#Html.DisplayFor(modelItem => item.SubscriptionCadenceCategory)
</div>
<div id="shoppingCartSubscriptionTotalPriceField" class="tableField col-xs-12 col-sm-12 col-md-12 col-lg-12">
CHF #Html.DisplayFor(modelItem => item.TotalPrice)
</div>
</a>
<a id="shoppingCartSubscriptionEditLink" class="tableField col-xs-1 col-sm-1 col-md-1 col-lg-1" href="#">
<i id="shoppingCartSubscriptionEdit" class="fas fa-edit"></i>
</a>
</div>
}
else
{
<div id="shoppingCartSingleOrderLineItemArea" class=" tableArea col-xs-offset-1 col-xs-10 col-sm-offset-1 col-sm-10 col-md-offset-1 col-md-10 col-lg-offset-2 col-lg-8">
#Html.HiddenFor(modelItem => item.ID, new { #class = "tableField col-xs-12 col-sm-12 col-md-12 col-lg-12" })
<a id="shoppingCartSingleOrderRemoveLink" class="tableField col-xs-1 col-sm-1 col-md-1 col-lg-1" href="#">
<i id="shoppingCartSingleOrderRemove" class="fas fa-trash-alt"></i>
</a>
<a id="shoppingCartSingleOrderLineItemLink" class="tableField col-xs-10 col-sm-10 col-md-10 col-lg-10" href="#Url.Action("ProductSingleOrder", "freshNclean", new { id = item.ID })">
<div id="shoppingCartSingleOrderProductNameField" class="tableField col-xs-7 col-sm-8 col-md-9 col-lg-9">
#Html.DisplayFor(modelItem => item.ProductName)
</div>
<div id="shoppingCartSingleOrderProductPriceField" class="tableField col-xs-5 col-sm-4 col-md-3 col-lg-3">
CHF #Html.DisplayFor(modelItem => item.SingleOrderPrice)
</div>
<div id="shoppingCartSingleOrderProductQuantityField" class="tableField col-xs-12 col-sm-12 col-md-12 col-lg-12">
#Html.DisplayFor(modelItem => item.SingleOrderQuantity) x
</div>
<div id="shoppingCartSingleOrderTotalPriceField" class="tableField col-xs-12 col-sm-12 col-md-12 col-lg-12">
CHF #Html.DisplayFor(modelItem => item.TotalPrice)
</div>
</a>
<a id="shoppingCartSingleOrderEditLink" class="tableField col-xs-1 col-sm-1 col-md-1 col-lg-1" href="#">
<i id="shoppingCartSingleOrderEdit" class="fas fa-edit"></i>
</a>
</div>
}
}
</div>
finally the Controller:
// GET: /freshNclean/ShoppingCart
[Authorize]
public ActionResult ShoppingCart(Orders model)
{
// define variables
var userID = User.Identity.GetUserId();
DateTime nowUTC = DateTime.Now.ToUniversalTime();
DateTime nowLocal = DateTime.Now.ToLocalTime();
// track user activity: get method is restricted to activity name and timestamp
var LOADED = new UserActivities
{
UserID = userID,
ActivityName = "ShoppingCart_Loaded",
ActivityTimeStampUTC = nowUTC,
ActivityLatitude = "n/a",
ActivityLongitude = "n/a",
ActivityLocation = "n/a"
};
DATADB.UserActivityList.Add(LOADED);
DATADB.SaveChanges();
return View(DATADB.LineItemList.Where(x => x.UserID == userID).Where(x => x.OrderNumber == 0).ToList());
}
I finally figured it out myself - not really. What I did is I changed the approach of writing to the shopping cart. But the end result is working.

Bootstrap glyphicon with MVC

Withour Razor syntax I can use glyphicon like that:
<div id="addIndirectCityBtn" class="btn btn-success btn-xs">
<span class="glyphicon glyphicon-plus"></span> Add
</div>
And it works perfect, glyphicon with textbox using razor syntax as below
#Html.TextBoxFor(model => model.From.City, new { #id = "cityFrom", #class = "form-control", #placeholder = "City", #style = "margin-bottom: 10px;" })
Where should I use glyphicon to have it in textbox or next to textbox
You can use input group in bootstrap, form-control class will put the object 100% width of box, so you need to group them.
Here is an example
<div class="input-group">
#Html.TextBoxFor(model => model.From.City, new { #id = "cityFrom", #class = "form-control", #placeholder = "City", #style = "margin-bottom: 10px;" }
<span class="input-group-addon"><i class="glyphicon glyphicon-plus"></i> Add</span>
</div>
How To use Glyphicons in Mvc Using Model
for example :
Model
public class Menu
{
public int Id { get; set; }
public string Name { get; set; }
public string Menuicon { get; set; }
}
Controller
[HttpPost]
public ActionResult Index(Menu m)
{
ViewBag.Message = m.Menuicon;
return View(m);
}
Index View
#model projectname.Models.Menu
#using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
#Html.LabelFor(Model => Model.Name)<br />
#Html.EditorFor(Model => Model.Name)<br />
#Html.LabelFor(Model => Model.Menuicon)<br />
#Html.EditorFor(Model => Model.Menuicon)<br />
<input type="submit" value="Save">
}
<br />
<div>
<span class="#ViewBag.Message"></span>
</div>
Result

Field required attribute acidentially invoked but clicking a button

I have these fields, and I implemented required attribute on them.
#using (Html.BeginForm("Edit", "ChannelsGrid", FormMethod.Post, new {name = "channelForm", #class = "channelForm", #enctype = "multipart/form-data"}))
{
<div class="form-group">
#Html.HiddenFor(model => Model.Id)
<div class="row">
<div class="col-md-6">
#Html.Label("Part/Location", new {#class = "control-label"})
#Html.TextBox("PartLocation", null, new { #class = "form-control", #required = "required" })
</div>
<div class="col-md-6">
#Html.Label("Index", new {#class = "control-label"})
#Html.TextBox("Index", null, new {#class = "form-control"})
</div>
</div>
<div class="row">
<div class="col-md-6">
#Html.Label("Measurement", new {#class = "control-label"})
#Html.DropDownListFor(model => model.Measurement, (SelectList)ViewBag.Measurements, "-- Select Measurement --", new { #class = "form-control", #required = "required" })
</div>
<div class="col-md-6">
#Html.Label("Location", new {#class = "control-label"})
#Html.DropDownList("Directions", ViewBag.DirectionTypes as List<SelectListItem>, "-- Select Direction --", new { #class = "form-control", #required = "required" })
</div>
</div>
<div class="row">
<div class="col-md-6">
#Html.LabelFor(model => model.ChannelGroupId, new {#class = "control-label"})
#Html.DropDownListFor(x => x.ChannelGroupId, Model.ChannelGroups, "Select Channel Group", new {#class = "form-control"})
#Html.ValidationMessageFor(model => model.ChannelGroupId)
</div>
<div class="col-md-3">
<label class="control-label"></label>
<a href="#" id="addChannelGroup" class="form-control" style="border: none">
<i class="fa fa-plus-circle">Add Group</i>
</a>
</div>
<div class="col-md-3">
<label class="control-label"></label>
<a href="#" id="addMeasurement" class="form-control" style="border: none">
<i class="fa fa-plus-circle">Add Measurement</i>
</a>
</div>
</div>
<br/>
<div class="row">
<div class="col-md-6">
#Html.Label("Channel name: ", new {id = "channelName", #class = "control-label"})
</div>
<div class="col-md-6">
#Html.TextBox("HiddenTextBox", null, new {#class = "hidden"})
<div class="col-md-1">
#Html.TextBoxFor(a => a.Name, new {#class = "hidden"})
</div>
</div>
</div>
</div>
<div class="row" id="pnlAddChannelGroupName" style="display: none">
<div class="col-md-6">
<label class="control-label">Channel Group Name :</label>
<input type="text" id="ChannelGroupName" name="ChannelGroupName" class="form-control"/>
<input type="button" value="Cancel" id="channelGroupButton" />
#*<button id="channelGroupButton">Cancel</button>*#
</div>
</div>
<div class="row" id="pnlMeasurement" style="display: none">
<div class="col-md-6">
#Html.Label("Measurement :", new {#class = "control-label"})
#Html.TextBox("MeasurementName", null, new {#class = "form-control"})
<input type="button" value="Cancel" id="measurementButton" />
#*<button id="measurementButton">Cancel</button>*#
</div>
</div>
}
I also have two buttons which are used to toggle other textboxes in this form. Here is the code.
<div class="row" id="pnlAddChannelGroupName" style="display: none">
<div class="col-md-6">
<label class="control-label">Channel Group Name :</label>
<input type="text" id="ChannelGroupName" name="ChannelGroupName" class="form-control"/>
<button id="channelGroupButton">Cancel</button>
</div>
</div>
<div class="row" id="pnlMeasurement" style="display: none">
<div class="col-md-6">
#Html.Label("Measurement :", new {#class = "control-label"})
#Html.TextBox("MeasurementName", null, new {#class = "form-control"})
<button id="measurementButton">Cancel</button>
</div>
</div>
The problem is whenever I click these two Cancel buttons in that field, the three fields seems to be invoked and there is brown border around the textbox dropdownlist. I guess these field have been submitted. But I thought I use button element instead of type button of an input so I can eliminate the submitting action of the button, right? Any clues? And how can I click these Cancel buttons withouts invoking validation in these other field?
Edited: I changed all the buttons to input type="button" and the validation of these other field dissapeared. Can someone explain?
This is my viewmodel:
namespace CrashTestScheduler.Entity.ViewModel
{
public class ChannelViewModel
{
public int Id { get; set; }
//[Display(Name = "Name")]
//[Required(ErrorMessage = "Please specify the channel name.")]
public string Name { get; set; }
public string Description { get; set; }
public string ChannelGroupName { get; set; }
public string MeasurementName { get; set; }
[Required(ErrorMessage = "Please select a channel group.")]
public int ChannelGroupId { get; set; }
public IEnumerable<SelectListItem> ChannelGroups { get; set; }
//[Required]
public string Measurement { get; set; }
}
}
The reason your form is submitting when clicking buttons is that the default action for a <button> element is type="submit" (refer documentation). You need to explicitly set the type attribute
<button type="button" ....>
However you have numerous issues with your approach.
By removing the [Required] attributes and using the required =
"required" html attribute, you now need to include manual
validation on the controller (never trust the user!)
Your mixing up Razor and manual html in the view, potentially
creating problems for model binding. Some of your label elements
wont work. (e.g. the first one is associated with a control named
"Part/Location" but there is no control named "Part/Location").
The user interface where your force users to click buttons to swap
between textboxes and dropdown lists is confusing and a sure way to
lose customers. Instead you should use an autocomplete control such
as jQuery Autocomplete which allows selection from a list or
direct text entry.
Your view model should contain validation attributes for its properties and can be simplified to
public class ChannelViewModel
{
public int Id { get; set; }
[Display(Name = "Part/Location")]
[Required]
public string PartLocation { get; set; }
public string Index { get; set; }
[Required]
public string Measurement { get; set; }
[Required]
[Display(Name = "Location")]
public int Direction { get; set; }
.... // other properties
public SelectList DirectionList { get; set; }
}
View
#Html.HiddenFor(model => Model.Id)
#Html.LabelFor(m => m.PartLocation, new {#class = "control-label"})
#Html.TextBoxFor(m => m.PartLocation, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.PartLocation)
#Html.LabelFor(m => m.Index, new {#class = "control-label"})
#Html.TextBoxFor(m => m.Index, new {#class = "form-control"})
#Html.LabelFor(m => m.Measurement, new {#class = "control-label"})
#Html.TextBoxFor(m => m.Measurement, new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Measurement)
#Html.LabelFor(m => m.Direction, new {#class = "control-label"})
#Html.DropDownListFor(m => m.Direction, Model.DirectionList, "-- Select Direction --", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Direction)
.... // more controls
The attach the autocomplete to $(#Measurement).autocomplete({...
This will give you client and server side validation out of the box, and a better user interface.

modelstate.isvalid not getting all the errors

I have this model :
[Required(ErrorMessage = "Please provide a valid EmailAddress")]
[EmailAddress]
[Display(Name = "Email")]
public string Email { get; set; }
[Required(ErrorMessage = "Please provide a company name")]
[Display(Name = "Company")]
public string CompanyName { get; set; }
[Required(ErrorMessage = "Please provide a username")]
[Display(Name = "Username")]
public string UserName { get; set; }
[Required(ErrorMessage = "Please select at least one language")]
public int[] SelectedLanguages { get; set; }
[Required(ErrorMessage = "Please select at least one business unit")]
public int[] SelectedBusinessUnits { get; set; }
Now when I do a post from my form using this model and I don't provide any of the values, I only get errormessages for Email, Company and UserName.
I don't get messages for the SelectedLanguages or the SelectedBusinessUnits.
What am i doing wrong?
THis is the view
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<hr />
#Html.ValidationSummary("", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(m => m.CompanyName, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.CompanyName, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.UserName, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.UserName, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.Email, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.TextBoxFor(m => m.Email, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#foreach (var la in Model.Languages)
{
<input type="checkbox"
name="SelectedLanguages" value="#la.Id" id="#la.Id" />
<label for="#la">#la.Title</label>
}
</div>
<div class="form-group">
#foreach (var bu in Model.BusinessUnits)
{
<input type="checkbox"
name="SelectedBusinessUnits" value="#bu.Id" id="#bu.Id" />
<label for="#bu.Id">#bu.Title</label>
}
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" class="btn btn-default" value="Register" />
</div>
</div>
}
I think you have to go the way of writing a custom validation routine accompanied with a ValidationAttribute. Don't think a simple "out-of-the-box" validator exists for checking if one or more values are present in an array.
Check out this SO post to point you in the right direction.
Basic setup:
public class ArrayContainsValueAttribute: ValidationAttribute
{
// your checks here (pseudo)
if(!array.Any())
return false;
return true;
}
[ArrayContainsValue(ErrorMessage = "Please select at least one business unit")]
public int[] SelectedBusinessUnits { get; set; }

Merge validation summary in single line(All required validation in single line,All invalid field validation in single line etc)

I am creating one ASP.NET MVC Application using JQuery,KnockOutJs etc.
I have one model for SignUp and use client side validation only.
public class SignUp
{
[Required(ErrorMessageResourceType = typeof(Messages), ErrorMessageResourceName = MessagesConst.UserNameIsRequired, AllowEmptyStrings = false)]
[StringLength(30, ErrorMessageResourceName = MessagesConst.UserNameLength, ErrorMessageResourceType = typeof(Messages))]
[RegularExpression(#"^[a-zA-Z ]*$", ErrorMessageResourceType = typeof(Messages), ErrorMessageResourceName = MessagesConst.OnlyAlphabetsAndSpaceAreAllowed)]
public string UserName { get; set; }
[RegularExpression(#"^\s*[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]+)*#[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)*(\.[A-Za-z]{2,4})[ ]*$", ErrorMessageResourceType = typeof(Messages), ErrorMessageResourceName = MessagesConst.InvalidEmail)]
[Required(ErrorMessageResourceType = typeof(Messages), ErrorMessageResourceName = MessagesConst.EmailIsRequired, AllowEmptyStrings = false)]
[StringLength(256, ErrorMessageResourceName = MessagesConst.EmailLength, ErrorMessageResourceType = typeof(Messages))]
public string Email { get; set; }
[DataType(DataType.Password)]
[StringLength(50, ErrorMessageResourceName = MessagesConst.PasswordRange, ErrorMessageResourceType = typeof(Messages),MinimumLength = 6)]
[Required(ErrorMessageResourceType = typeof(Messages), ErrorMessageResourceName = MessagesConst.PasswordRequired, AllowEmptyStrings = false)]
public string Password { get; set; }
[DataType(DataType.Password)]
[Compare("Password", ErrorMessageResourceName = MessagesConst.InvalidConfirmPassword, ErrorMessageResourceType = typeof(Messages))]
public string ConfirmPassword { get; set; }
public bool IsNewsLetter { get; set; }
public bool RememberMe { get; set; }
}
I m showing validation summary on view.
#using (Html.BeginForm("Registration", "Home", FormMethod.Post, new { id = "frmRegistration" }))
{
<div class="msg">
#Html.ValidationSummary(false)
</div>
<h1 class="title">#UserResource.lblSignUp</h1>
<div class="content_box signup">
<div class="sign_up">
<div class="left">
<div class="logo">
<a href="/" title="Home">
</a>
</div>
<div class="feat_text">
<h1>#LayoutResources.tglnCF</h1>
<p class="subtitle">#LayoutResources.tglnSubTitleCF</p>
</div>
<div class="bottom_box">
<strong>#UserResource.lblAlreadyAccountOnSocialnetwork</strong><br>
<span class="sing_in_direct">#UserResource.lblSignIn directly from here.</span>
</div>
</div>
<div class="right">
#*Remove Placeholders for validation issue.*#
<div class="control-group">
<label class="blue">#UserResource.lblUserName</label>
<div class="controls">
#Html.TextBoxFor(m => m.UserName, new { #data_bind = "value:UserName, valueUpdate:['afterkeydown','propertychange','input']", placeholder = Placeholders.UserName, want_live_validation = true })
<span class="help-inline">
<span class="sprite"></span>
</span>
#*#Html.ValidationMessageFor(m => m.UserName)*#
</div>
</div>
<div class="control-group">
<label class="blue">#UserResource.lblEmail</label>
<div class="controls">
#Html.TextBoxFor(m => m.Email, new { #data_bind = "value:Email, valueUpdate:['afterkeydown','propertychange','input']", placeholder = Placeholders.Email, want_live_validation = true })
<span class="help-inline">
<span class="sprite"></span>
</span>
#*#Html.ValidationMessageFor(m => m.Email)*#
</div>
</div>
<div class="control-group">
<label class="blue">#UserResource.lblPassword</label>
<div class="controls">
#Html.PasswordFor(x => x.Password, new { #data_bind = "value:Password, valueUpdate:['afterkeydown','propertychange','input']", title = ToolTipResources.ttPassword, placeholder = Placeholders.Password, #class = "tooltip", want_live_validation = true })
<span class="help-inline">
<span class="sprite"></span>
</span>
#*#Html.ValidationMessageFor(m => m.Password)*#
<div class="m-t5">
<div data-bind="css:PasswordStrengthClass()"></div>
<span id='result' data-bind="text:PasswordStrengthMessage()"></span>
</div>
</div>
</div>
<div class="control-group">
<label class="blue">#UserResource.lblConfirmPassword</label>
<div class="controls">
#Html.PasswordFor(m => m.ConfirmPassword, new { #data_bind = "value:ConfirmPassword, valueUpdate:['afterkeydown','propertychange','input']", placeholder = Placeholders.ConfirmPassword, want_live_validation = true })
<span class="help-inline">
<span class="sprite"></span>
</span>
#*#Html.ValidationMessageFor(m => m.ConfirmPassword)*#
</div>
</div>
<label class="checkbox blue" for="checkbox1">
#Html.CheckBoxFor(m => m.IsNewsLetter, new { name = "check1", id = "checkTermAndPolicy" })
#UserResource.lblDiscoverNewProjectWithWeeklyNewsLetter
</label>
<p class="terms_text">
#UserResource.lblBySignInYouAgreeToOur #UserResource.lblTermsOfUse #UserResource.lblAnd #UserResource.lblPrivacyPolicy.
</p>
<div>
<p class="errorMassage"></p>
</div>
<input type="submit" value="SIGN UP">
</div>
<div class="clear"></div>
</div>
</div>
}
currently summary appear like
but i want to customize that summary like all validation that fire for required field will show like(User Name,Email,Password Required.)
or all validation that fire for invalid field will show like(invalid email address User Name,Email.)
You could try #Html.ValidationSummary().ToString().Replace("\r\n", "").Replace("\n", "").Replace("\r", "")
I'm not sure how validationsummary spits out its linebreaks, however, so you can probably find out and cut that down.

Resources