MVC5 ComponentModel.DataAnnotation is not working - asp.net-mvc

Please tell me why ComponentModel.DataAnnotations is not working here i have done every thing but in vain so tell me where i have mistakes in this code. here i am posting my view along with model.
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<form>
<div id="par" class="form-horizontal">
<hr />
#Html.ValidationSummary(true)
<div class="form-group">
#Html.LabelFor(model => model.BrandCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BrandCode, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.BrandCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductSubGroupCode, new { #class = "control-label col-md-2 col-ld-2 col-sd-2" })
<div class="col-md-10">
#(Html.Kendo().ComboBoxFor(model => model.ProductSubGroupCode)
.DataTextField("ProductSubGroupName")
.DataValueField("ProductSubGroupCode")
.DataSource(d => d.Read(r => r.Action("GetProductSubGroup", "Product")))
.Placeholder("Select Product Sub Group...")
.Suggest(true)
.HighlightFirst(true)
)
#Html.ValidationMessageFor(model => model.ProductSubGroupCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductGroupCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#(Html.Kendo().ComboBoxFor(model => model.ProductGroupCode)
.MinLength(100)
.DataTextField("ProductGroupName")
.DataValueField("ProductGroupCode")
.DataSource(d => d.Read(r => r.Action("GetProductGroup", "Product")))
.Placeholder("Select Product Group...")
.Suggest(true)
.HighlightFirst(true)
)
#Html.ValidationMessageFor(model => model.ProductGroupCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BrandName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BrandName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BrandName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BrandDescription, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BrandDescription, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BrandDescription, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Active, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.CheckBoxFor(model => model.Active)
#Html.ValidationMessageFor(model => model.Active, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SortOrder, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SortOrder, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SortOrder, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" id="Save" class="btn btn-info" />
<p id="content"></p>
</div>
</div>
</form>
This is the model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
public class BrandViewModels
{
[Display(Name = "Brand Code")]
[Required(ErrorMessage = "Brand Code is required")]
[RegularExpression(#"(\S)+", ErrorMessage = "White space is not allowed.")]
[Remote("IsUniqueBrandCode", "Product", AdditionalFields = "BrandCode", HttpMethod = "POST", ErrorMessage = "Brand Code already exists.")]
public string BrandCode { get; set; }
public int CompanyId { get; set; }
public List<ProductSubGroupList> ProductSubGroupList { get; set; }
public List<ProductGroupList> ProductGroupList { get; set; }
[Required(ErrorMessage = "Please select product group")]
[Display(Name = "Product Group")]
public string ProductGroupCode { get; set; }
[Required(ErrorMessage = "Please select product sub group")]
[Display(Name = "Product Sub Group")]
public string ProductSubGroupCode { get; set; }
[Required(ErrorMessage = "Brand name is required")]
[Display(Name = "Brand Name")]
public string BrandName { get; set; }
[Required(ErrorMessage = "Description is required")]
[Display(Name = "Description")]
public string BrandDescription { get; set; }
[Display(Name = "Active")]
public bool Active { get; set; }
[Display(Name = "Sort Order")]
[Required(ErrorMessage = "Sorting order is required")]
public int? SortOrder { get; set; }
}

Please check if you have following Appsettings in Web Config
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
Please refer Data Anotation validation

Here is my code Working perfect i seen your Code you may have these Error,
you should use #using (Html.BeginForm()) instead of <form>
#Html.ValidationSummary(false) in place of #Html.ValidationSummary(true)
please see my Code.
<div class="container">
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>mymodel</h4>
<hr />
#Html.ValidationSummary(false)
<div class="form-group">
#Html.LabelFor(model => model.id, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.id)
#Html.ValidationMessageFor(model => model.id)
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.name, new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.name)
#Html.ValidationMessageFor(model => model.name)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
</div>
<div>
#Html.ActionLink("Back to List", "Index")
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

Related

Passing ViewModel List Data to controller

I have a ViewModel as such:
public class AddNewsModel
{
public List<CategoriesModel> Category { get; set; }
public NewsModel NewsModel { get; set; }
}
where Category contains:
public class CategoriesModel
{
public string Name { get; set; }
public int ID { get; set; }
}
and NewsModel contains:
public class NewsModel
{
public int ID { get; set; }
public string Category { get; set; }
public String Headline { get; set; }
public string Source { get; set; }
public DateTime Publish_Date { get; set; }
public string Text { get; set; }
public string Summary { get; set; }
public string TimeAgo { get; set; }
public string ImageURL { get; set; }
public string CategoryID { get; set; }
}
I have a View where I take form input for News using NewsModel, but I want to display possible categories as a dropdown list or select Tag from the CategoriesModel.
This is My View:
<h2>Add a News Article</h2>
#if (TempData["Success"] != null)
{
<p class="alert alert-success" id="successMessage">#TempData["Success"]</p>
}
#using (Html.BeginForm("AddNews", "Admin", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal" id="addNews">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("News ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-1">
#Html.EditorFor(model => model.NewsModel.ID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Category, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.Category, new SelectList(Model.Category), "Select Category")
#*<div class="col-md-2">
<select form="addNews" id="NewsModel_Category" name="NewsModel.Category">
#foreach (var item in Model.Category)
{
<option value="#item.Name">#item.Name</option>
}
</select>
</div>*#
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Headline, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.Headline, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Headline, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Source, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.Source, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Source, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Publish Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.NewsModel.Publish_Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Publish_Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Text, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.TextAreaFor(model => model.NewsModel.Text, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Text, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Summary, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.TextAreaFor(model => model.NewsModel.Summary, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Summary, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.ImageURL, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.ImageURL, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.ImageURL, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
This line of code:
#Html.DropDownListFor(model => model.Category, new SelectList(Model.Category), "Select Category")
gets all the categories, but only displays them as the model I have imported int the view, viz. "MVCApplication.Models.AddNewsModel", instead of a category like "World" or "Tech"
This code that I have commented, returns null when i try to get the data in my HTTPPost controller action using formcollection. I have tried using the ID that i have provided as: string x= formCollection["category"];
<div class="col-md-2">
<select form="addNews" id="category" name="category">
#foreach (var item in Model.Category)
{
<option value="#item.Name">#item.Name</option>
}
</select>
</div>
How can I show the categories in my View, as well as get the value in the controller?
Any help would be appreciated.
Edit:
I am populating The Categories list in my controller action as:
public ActionResult AddNews()
{
AddNewsModel AddNewsModel = new AddNewsModel();
AddNewsModel.Categories = new NewsArticles().GetCategories();
return View(AddNewsModel);
}
Changing my model to an Ienumerable instead of list causes errors in my controller I cannot seem to solve.
your model should be like this:
public class AddNewsModel
{
public IEnumerable<SelectListItem> CategorySelectList { get; set; }
public int CategoryId {get; set;}
public NewsModel NewsModel { get; set; }
}
and in the view :
#Html.DropDownListFor(model => model.CategoryId, Model.CategorySelectList, "Select Category")
for more details -> link
You should have both Cateogory and List with all categories in the model
public class AddNewsModel
{
public int Category { get; set; }
public IEnumerable<SelectListItem> Categories { get; set;}
public NewsModel NewsModel { get; set; }
}
View
update your dropdownlist with list.
<h2>Add a News Article</h2>
#if (TempData["Success"] != null)
{
<p class="alert alert-success" id="successMessage">#TempData["Success"]</p>
}
#using (Html.BeginForm("AddNews", "Admin", FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal" id="addNews">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.Label("News ID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-1">
#Html.EditorFor(model => model.NewsModel.ID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.ID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Category, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.Category, Model.Categories, "Select Category")
#*<div class="col-md-2">
<select form="addNews" id="NewsModel_Category" name="NewsModel.Category">
#foreach (var item in Model.Category)
{
<option value="#item.Name">#item.Name</option>
}
</select>
</div>*#
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Headline, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.Headline, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Headline, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Source, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.Source, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Source, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.Label("Publish Date", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.NewsModel.Publish_Date, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Publish_Date, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Text, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.TextAreaFor(model => model.NewsModel.Text, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Text, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.Summary, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.TextAreaFor(model => model.NewsModel.Summary, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.Summary, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.NewsModel.ImageURL, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-6">
#Html.EditorFor(model => model.NewsModel.ImageURL, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.NewsModel.ImageURL, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}

Cannot save values from form to database

I am trying to write my first ASP.NET MVC application with Entity Framework (code first).
I am trying to insert data from form to specific table in database but it does not work. When I press "Submit" button, page is refreshing but table still has not any value. There is no error on page or in console.
Could you please take a look on code and help me ?
Below is my code:
View:
#model VeterinaryApp.Models.Clients
#{
ViewBag.Title = "AddClient";
Layout = "~/Views/SharedViews/_MainLayout.cshtml";
}
<h2>AddClient</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Clients</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Surname, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Surname, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Surname, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Phone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
Controller:
public class AddClientController : Controller
{
// GET: AddClient
public ActionResult AddClient()
{
return View();
}
//POST
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ClientsId, Name, Surname, Email, Phone")] Clients clients)
{
if (ModelState.IsValid)
{
using (StoreContext db = new StoreContext()) //DbContext
{
db.Clients.Add(clients);
db.SaveChanges();
return RedirectToAction("Index");
}
}
return View(clients);
}
}
Model
public class Clients
{
public int ClientsId { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Email { get; set; }
public int Phone { get; set; }
public virtual ICollection<BookVisit> BookedVisits { get; set; }
public virtual ICollection<Animals> OwnedAnimals { get; set; }
}

Getting vailidation anomalies in MVC

I'm following this (https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/getting-started-with-mvc/getting-started-with-mvc-part7), but I am seeing some strange things I when I view the webpage.
1) The ReleaseDate says its a required filed (even though its not marked as such in the code) , and I cannot see why its doing this.
and
2) the Price "works" if the values is 100.50, or less . if its 100.51 or higher, then the message kicks in. My understanding is that the message should kick in # 100.01... or am I wrong ?
namespace Movies.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class Movie
{
public int Id { get; set; }
[Required(ErrorMessage = "Titles are required")]
public string Title { get; set; }
public System.DateTime ReleaseDate { get; set; }
public string Genre { get; set; }
[Required(ErrorMessage = "The Price is required.")]
[Range(5, 100, ErrorMessage = "Movies cost between £5 and £100.")]
public decimal Price { get; set; }
}
}
Could someone point out what I'm doing wrong ?
thanks
view code is
#model Movies.Models.Movie
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Movie</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Title, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Title, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ReleaseDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ReleaseDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ReleaseDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Genre, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Genre, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Genre, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Price, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Price, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Price, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
First question.
Make your DateTime nullable like this:
public System.DateTime? ReleaseDate { get; set; }
Second question:
Specify Range number type to double with literal d like this:
[Range(5d, 100d, ErrorMessage = "Movies cost between £5 and £100.")]
public decimal Price { get; set; }

how to bind dropdown using foreign key in mvc

trying to bind the BrandName column drop down but i am unable to get it..can any one help me to get this.
Here is my code:
public class ApplicationUser : IdentityUser
{
[Column(Order = 1), ForeignKey("Brands")]
public int BrandId { get; set; }
public virtual Brands Brands { get; set; }
}
public class Brands
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string BrandName { get; set; }
public string ContactPerson { get; set; }
public string ContactNumber { get; set; }
}
controller code:
public ActionResult Register()
{
ViewBag.Name = new SelectList(context.Roles.Where(u => !u.Name.Contains("Admin"))
.ToList(), "Name", "Name");
return View();
}
Register.chstml code:
#using (Html.BeginForm("Register", "Account", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
<h4>Create a new account.</h4>
<hr />
#Html.ValidationSummary()
<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.Password, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.Password, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(m => m.ConfirmPassword, new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.PasswordFor(m => m.ConfirmPassword, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.Label("User Role", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownList("UserRoles", (SelectList)ViewBag.Name, " ", new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.Label("Brand Id", new { #class = "col-md-2 control-label" })
<div class="col-md-10">
#Html.DropDownList("BrandId",(SelectList)ViewBag.BrandNamenew,"",new{ #class = "form-control" })
</div>
</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>
}
how to write controller and cshtml code to bind BrandId dropdown

Don't fire a required validator for

I have the following model:
public class Model1
{
[Required(ErrorMessage="E1")]
public string Name { get; set; }
[Required(ErrorMessage="E2")]
[RegularExpression(".+\\#.+\\..+")]
public string Email { get; set; }
[Required(ErrorMessage="E3")]
public bool WillAttend { get; set; }
}
controller action:
public ActionResult Model1()
{
Model1 m = new Model1();
return View(m);
}
and view:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Model1</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Email, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.WillAttend, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.WillAttend)
#Html.ValidationMessageFor(model => model.WillAttend, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
problem is required validator for WillAttend property does not work. Even in action method, ModelState.IsValid is true. Why and how to do WillAttend is required ?
At the moment, your required-attribute just checks whether a value was specified. Since a boolean is either true or false, the validation will never fail.
You can, mark the boolean as nullable:
public bool? WillAttend { get; set; }
or you can try to make a custom validator if you are trying to force them to check the box, such as in this link.

Resources