how to bind dropdown using foreign key in mvc - asp.net-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

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

Display name of Identity User who created and last updated record when ID is saved

I must not be searching with the correct phrases. This is a simple concept and I’ve done it in other languages and frameworks with ease.
I’m saving the UserID for the person who created the record and the UserID who last updated the record. Instead of displaying the UserID, I want to display the User.FirstName + ‘ ‘ + User.LastName.
The way I have it currently the LastEditBy and CreateBy is displayed on the page as blank.
Controller: I get the customer model and manually map the model to the customerViewModel then pass it to my partial view.
public ActionResult Edit(int customerId)
{
Customer customer = DbContext.Customers.FirstOrDefault(x => x.CustomerId == customerId);
CustomerViewModel customerViewModel = MapToViewModel(customer);
customerViewModel.UserSelectList = GetUserGroupList();
UserManager<ApplicationUser> _userManager = HttpContext.GetOwinContext().Get<ApplicationUserManager>();
var CreateByUser = _userManager.FindById(customerViewModel.CreateById);
var EditByUser = _userManager.FindById(customerViewModel.LastEditById);
customerViewModel.CreateBy = CreateByUser.FirstName + " " + CreateByUser.LastName;
customerViewModel.LastEditBy = EditByUser.FirstName + " " + EditByUser.LastName;
if (Request.IsAjaxRequest()) {
return PartialView("_CustomerEditPartial", customerViewModel);
}
return View("_CustomerEditPartial", customerViewModel);
}
The CustomerViewModel:
public class CustomerViewModel : DbContext{
public CustomerViewModel(): base("name=CustomerViewModel")
{
}
[Key]
public int CustomerId { get; set; }
[MaxLength(128), ForeignKey("ApplicationUser")]
public string UserId { get; set; }
public SelectList UserSelectList { get; set; }
#region additional Fields
// This overrides default conventions or data annotations
[Required(ErrorMessage = "Please enter your first name.")]
[StringLength(50)]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required(ErrorMessage = "Please enter your last name.")]
[StringLength(100)]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime CreateDate { get; set; } = DateTime.Now;
public string CreateById { get; set; }
[NotMapped]
public string CreateBy { get; set; }
public string LastEditById { get; set; }
[NotMapped]
public string LastEditBy { get; set; }
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
public DateTime LastEditDate { get; set; } = DateTime.Now;
public virtual ApplicationUser ApplicationUser { get; set; }
}
public class UserGroupList
{
public string Value { get; set; }
public string Text { get; set; }
}
My partial view page: _CustomerEditPartial.cshtml
#model WOA.ViewModels.CustomerViewModel
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" daa-dismiss="modal" aria-hidden="True">x</button>
<h4 class="modal-title">Edit Customer</h4>
</div>
#using (Ajax.BeginForm("Edit", "Customers", null, new AjaxOptions { HttpMethod = "Post", OnFailure = "OnFail" }, new { #class = "form-horizontal", role = "form" })) {
<div class="modal-body">
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.CustomerId)
<div class="form-group">
#Html.LabelFor(model => model.UserId, "UserId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.UserId, ViewData.Model.UserSelectList, "Select One", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.UserId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreateDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.CreateDate, new { #readonly = "readonly" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreateBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.CreateBy, new { #readonly = "readonly" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastEditBy, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.LastEditBy, new { #readonly = "readonly" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastEditDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.LastEditDate, new { #readonly = "readonly" })
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" value="Save changes" />
</div>
</div>
</div>
<script type="text/javascript">
function OnSuccess() {
alert("success");
}
function OnFail() {
alert("fail");
}
function OnComplete() {
alert("Complete");
}
</script>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
</div>
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
I have updated my code, it is working now, however I do not believe it is the proper way to do this.
I believe I should be able to return the additional values I need via Linq on the initial call and not make two more trips to the database for the additional values.
I have not been able to figure out a way to make this work with Linq.
Thank you in advance for your time and effort.

The current request for action ... on controller type ... is ambiguous between the following action methods

When I run the application on browser with ~/Person/New the result is
The current request for action 'New' on controller type 'PersonController' is ambiguous between the following action method System.Web.Mvc.ActionResult New() on type PersonMVC.Controllers.PersonController System.Web.Mvc.ActionResult New(PersonMVC.Models.Person) on type PersonMVC.Controllers.PersonController
Model
namespace PersonMVC.Models
{
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public string LastName { get; set; }
[Required]
[DisplayName("Social Sequrity Number")]
[MinLength(11, ErrorMessage ="Social Security Number Must be 11 digit.")]
[MaxLength(11, ErrorMessage ="")]
public string SocialSecurityNumber { get; set; }
[DisplayFormat(DataFormatString ="{0:dd.MM.yyyy}")]
public DateTime BirthDay { get; set; }
}
}
-View
#model PersonMVC.Models.Person
#{
ViewBag.Title = "New";
}
<h2>New</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Person</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.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SocialSecurityNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SocialSecurityNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SocialSecurityNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.BirthDay, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.BirthDay, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.BirthDay, "", 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>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Controller
namespace PersonMVC.Controllers
{
public class PersonController : Controller
{
public ActionResult New()
{
return View();
}
[HttpPost]
public ActionResult New(Person newPerson)
{
bool isTrue = ModelState.IsValid;
return View();
}
}
}
you need to decorate the method with appropriate http verb. Otherwise it will be considered as HttpPost usually.
i think adding [HttpPost] to the controller method would solve the problem

MVC5 ComponentModel.DataAnnotation is not working

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>

Resources