Why returened values of form are null in MVC project? - asp.net-mvc

I try to update a record .I use validation in this view but always
ModelState.IsValid = false
I search on the internet and found that I should check errors with this code :
var errors = ModelState.Values.SelectMany(v => v.Errors);
Now I can not understand that what is problem?
In this image you can see that all parameters are null.
Please advice.
View:
#model TravelEnterAdminTemplate.Models.LG.ResturantModel
#{
ViewBag.Title = "EditRestaurant";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#*fck Editor*#
<script type="text/javascript" src="#Url.Content("~/Content/Adminex/js/fckEditor/fckeditor.js")"></script>
<script type="text/javascript">
window.onload = function () {
var sBasePath = '#Url.Content("~/Content/Adminex/js/fckeditor/")';
var oFCKeditor = new FCKeditor('Restaurants_Description');
oFCKeditor.BasePath = sBasePath;
oFCKeditor.Height = 450;
oFCKeditor.Width = 800;
oFCKeditor.ReplaceTextarea();
//----------------------DescriptionEn---------------------
var oFCKeditorEn = new FCKeditor('Restaurants_DescriptionEn');
oFCKeditorEn.BasePath = sBasePath;
oFCKeditorEn.Height = 450;
oFCKeditorEn.Width = 800;
oFCKeditorEn.ReplaceTextarea();
}
</script>
<div class="container">
<h4>ویرایش رستوران</h4>
<hr />
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Restaurants.id)
<div class="row">
<div class="col-md-4 pull-right">
#Html.LabelFor(model => model.Restaurants.RestaurantName, htmlAttributes: new { #lablefor = "RestaurantName" })
#Html.EditorFor(model => model.Restaurants.RestaurantName, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-4 pull-right">#Html.ValidationMessageFor(model => model.Restaurants.RestaurantName, "", new { #class = "text-danger" })</div>
</div>
<div class="row">
<div class="col-md-7 pull-right">
#Html.LabelFor(model => model.Restaurants.Address, htmlAttributes: new { #lablefor = "Address" })
#Html.EditorFor(model => model.Restaurants.Address, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-4 pull-right">#Html.ValidationMessageFor(model => model.Restaurants.Address, "", new { #class = "text-danger" })</div>
</div>
<div class="row">
<div class="col-md-2 pull-right">
#Html.LabelFor(model => model.Restaurants.City.Country.NameFa, htmlAttributes: new { #lablefor = "CountryId" })
#Html.DropDownList("CountryId", null, new { #class = "form-control" })
</div>
</div>
<div class="row">
<div class="col-md-2 pull-right">
<div>
#Html.LabelFor(model => model.Restaurants.City.NameFA, htmlAttributes: new { #lablefor = "CityId" })
#Html.DropDownList("CityId", null, new { #class = "form-control" })
</div>
</div>
</div>
<div class="row">
<div class="col-md-2 pull-right">
#Html.LabelFor(model => model.Restaurants.Tell, htmlAttributes: new { #lablefor = "Tell" })
#Html.EditorFor(model => model.Restaurants.Tell, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-4 pull-right">#Html.ValidationMessageFor(model => model.Restaurants.Tell, "", new { #class = "text-danger" })</div>
</div>
<div class="row">
<div class="col-md-4 pull-right">
#Html.LabelFor(model => model.Restaurants.Title, htmlAttributes: new { #lablefor = "Title" })
#Html.EditorFor(model => model.Restaurants.Title, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-4 pull-right">
#Html.ValidationMessageFor(model => model.Restaurants.Title, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-3 pull-right">
#Html.LabelFor(model => model.Restaurants.InsertDate, htmlAttributes: new { #lablefor = "InsertDate" })
#Html.EditorFor(model => model.Restaurants.InsertDate, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-4 pull-right">#Html.ValidationMessageFor(model => model.Restaurants.InsertDate, "", new { #class = "text-danger" })</div>
</div>
<div class="row">
<div class="col-md-5 pull-right">
#Html.LabelFor(model => model.Restaurants.Summary, htmlAttributes: new { #lablefor = "Summary" })
#Html.EditorFor(model => model.Restaurants.Summary, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-4 pull-right">
#Html.ValidationMessageFor(model => model.Restaurants.Summary, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-8 pull-right">
#Html.LabelFor(model => model.Restaurants.Description, htmlAttributes: new { #lablefor = "Description" })
#Html.EditorFor(model => model.Restaurants.Description, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-4 pull-right">#Html.ValidationMessageFor(model => model.Restaurants.Description, "", new { #class = "text-danger" })</div>
</div>
<div class="row">
<div class="col-md-3 pull-right">
#Html.LabelFor(model => model.Restaurants.LocationX, htmlAttributes: new { #lablefor = "LocationX" })
#Html.EditorFor(model => model.Restaurants.LocationX, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-4 pull-right">
#Html.ValidationMessageFor(model => model.Restaurants.LocationX, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-3 pull-right">
#Html.LabelFor(model => model.Restaurants.LocationY, htmlAttributes: new { #lablefor = "LocationY" })
#Html.EditorFor(model => model.Restaurants.LocationY, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-4 pull-right">#Html.ValidationMessageFor(model => model.Restaurants.LocationY, "", new { #class = "text-danger" })</div>
</div>
<div class="row">
<div class="col-md-3 pull-right">
#Html.LabelFor(model => model.Restaurants.Website, htmlAttributes: new { #lablefor = "Website" })
#Html.EditorFor(model => model.Restaurants.Website, new { htmlAttributes = new { #class = "form-control website" } })
</div>
<div class="col-md-4 pull-right">#Html.ValidationMessageFor(model => model.Restaurants.Website, "", new { #class = "text-danger" })</div>
</div>
<div class="row">
<div class="col-md-5 pull-right">
<div class="checkbox">
#Html.LabelFor(model => model.Restaurants.IsActive, htmlAttributes: new { #lablefor = "IsActive" })
#Html.EditorFor(model => model.Restaurants.IsActive)
</div>
<div class="col-md-4 pull-right">
#Html.ValidationMessageFor(model => model.Restaurants.IsActive, "", new { #class = "text-danger" })
</div>
</div>
</div>
#*-------------------------------------------------------------------------------------*#
<fieldset dir="ltr" class="fieldsetEn">
<legend>English Content</legend>
<div class="row">
<div class="col-md-5">
<div class="checkbox checkboxEn">
#Html.LabelFor(model => model.Restaurants.IsEnglish, htmlAttributes: new { #Labelfor = "IsEnglish" })
#Html.EditorFor(model => model.Restaurants.IsEnglish)
</div>
<div class="col-md-4 ">
#Html.ValidationMessageFor(model => model.Restaurants.IsEnglish, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="row">
<div class="col-md-4">
#Html.LabelFor(model => model.Restaurants.RestaurantNameEn, htmlAttributes: new { #Labelfor = "RestaurantNameEn" })
#Html.EditorFor(model => model.Restaurants.RestaurantNameEn, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-4 ">
#Html.ValidationMessageFor(model => model.Restaurants.RestaurantNameEn, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-7">
#Html.LabelFor(model => model.Restaurants.AddressEn, htmlAttributes: new { #Labelfor = "AddressEn" })
#Html.EditorFor(model => model.Restaurants.AddressEn, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-4 ">
#Html.ValidationMessageFor(model => model.Restaurants.AddressEn, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-4">
#Html.LabelFor(model => model.Restaurants.TitleEn, htmlAttributes: new { #Labelfor = "TitleEn" })
#Html.EditorFor(model => model.Restaurants.TitleEn, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-4 ">
#Html.ValidationMessageFor(model => model.Restaurants.TitleEn, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-5">
#Html.LabelFor(model => model.Restaurants.SummaryEn, htmlAttributes: new { #Labelfor = "" })
#Html.EditorFor(model => model.Restaurants.SummaryEn, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-4 ">
#Html.ValidationMessageFor(model => model.Restaurants.SummaryEn, "", new { #class = "text-danger" })
</div>
</div>
<div class="row">
<div class="col-md-7">
#Html.LabelFor(model => model.Restaurants.DescriptionEn, htmlAttributes: new { #Labelfor = "DescriptionEn" })
#Html.TextAreaFor(model => model.Restaurants.DescriptionEn, new { htmlAttributes = new { #class = "form-control" } })
</div>
<div class="col-md-4 ">
#Html.ValidationMessageFor(model => model.Restaurants.DescriptionEn, "", new { #class = "text-danger" })
</div>
</div>
</fieldset>
#{
string path = System.Configuration.ConfigurationManager.AppSettings["ImageEdit"];
}
<div class="row text-right">
#foreach (var item in Model.PhotoTables)
{
<text>
<div class="col-xs-2 col-wrapper pull-right">
<div class="image-wrapper">
<img src="#Url.Content(path + item.PhotoName)" alt="" class=" img-responsive" />
<img class="delimg" src="~/Content/Adminex/images/delete-icons.png" id="#item.Id" alt="حذف تصویر" />
</div>
</div>
</text>
}
</div>
<br />
<br />
<div class="row">
<div class="col-md-4"></div>
<div class="col-md-4">
<input type="submit" value="ذخیره تغییرات" class="btn btn-info btn-block" />
</div>
<div class="col-md-4"></div>
</div>
</div>
}
</div>
<script src="~/Content/Adminex/js/ajax/Restaurants_Edit.js"></script>
#section Scripts {
#Scripts.Render("~/bundles/jqueryValidation")
}
Model:
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace TravelEnterAdminTemplate.Models.dbModel
{
using System;
using System.Collections.Generic;
public partial class Restaurant
{
public int id { get; set; }
public int CityId { get; set; }
public string RestaurantName { get; set; }
public string Address { get; set; }
public string Tell { get; set; }
public string Title { get; set; }
public System.DateTime InsertDate { get; set; }
public string Summary { get; set; }
public string Description { get; set; }
public string LocationX { get; set; }
public string LocationY { get; set; }
public string UserId { get; set; }
public int Visitor { get; set; }
public bool IsActive { get; set; }
public string Website { get; set; }
public int CategoryId { get; set; }
public string RestaurantNameEn { get; set; }
public string AddressEn { get; set; }
public string TitleEn { get; set; }
public string SummaryEn { get; set; }
public string DescriptionEn { get; set; }
public Nullable<int> VisitorEn { get; set; }
public bool IsEnglish { get; set; }
public virtual AspNetUser AspNetUser { get; set; }
public virtual City City { get; set; }
}
}

I sometimes use Code like this for debugging. (written from memory)
var errors = new List<KeyValuePair<string, string>();
for (int i = 0; i < ModelState.Keys.Count; i++)
{
var value = ModelState.Values.ElementAt(i);
if value.Errors.Any()
{
foreach (var error in Value.Errors)
{
errors.Add(new KeyValuePair<string, string>
(ModelState.Keys.ElementAt(i),
error.Message ?? error.Exception.Message);
}
}
}
This should help you diagnose which model elements are causing validation errors.
A common reason for server side validation errors is that a non-nullable int or Guid Id field is included in the model but is either not included in the view, or is hidden and / or not populated.

that's not how you post though.
your post method should be very simple, something like :
public async Task Post(ModelClass someName)
so you basically have a model class. That class needs to be decorated with [DataContract] which needs a reference to System.Runtime.Serialization
Each property in that class that you want to be able to send as part of a post needs to then have a DataMember tag on it. This way the default serialization used by the MVC engine will kick in and accept your post as long as the names passed by the form match those in the model exactly. This applies especially when we work with WebApi. For pure MVC work we don't need those tags
Always do model validation first :
if (!ModelState.IsValid) then return an error code
every validation item you have on your model properties needs to happen before the ModelState will be valid.
Here's a basic example which I wrote a few years ago, maybe it will help :
mvc article

Related

The model item passed into the dictionary is of type 'System.Collections.Generic.List but this dictionary requires a model item of type 'XXX.XXX.XXX'

I am trying to use strongly typed dropdownlist for my application. I have textbox fields as well. But when i pass #model Aayumitra.Models.RegisterViewModel
#using Aayumitra.Models; I am getting below error.
The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[System.Web.Mvc.SelectListItem]', but this dictionary requires a model item of type 'XXX.XXX.XXX'.
AccountViewModel
public class RegisterViewModel
{
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public IEnumerable<SelectListItem> Genders { get; set; }
}
Controller
private static List<SelectListItem> GetGenders()
{
AayumitraDBEntities db = new AayumitraDBEntities();
List<SelectListItem> GenderList = (from p in db.Genders.AsEnumerable()
select new SelectListItem
{
Text = p.GenderType,
Value = p.GenderId.ToString()
}).ToList();
//Add Default Item at First Position.
GenderList.Insert(0, new SelectListItem { Text = "--Select Gender--", Value = "" });
return GenderList;
}
//
// GET: /Account/UpdatePatient
[AllowAnonymous]
public ActionResult UpdatePatient()
{
List<SelectListItem> GenderList = GetGenders();
return View(GenderList);
}
View
#model Aayumitra.Models.RegisterViewModel
#using Aayumitra.Models;
#using (Html.BeginForm())
{
<div class="row">
<div class="col-md-4">
<div class="profile-container">
<div class="profile">
<img src="~/Content/images/logo.png" width="100" />
</div>
<div class="profile-info">
<p>
#Html.TextBox("FullName", User.Identity.Name.ToString(), new { #readonly = "readonly", #disabled = "disabled" })
</p>
</div>
</div>
</div>
</div>
<div class="dropdown-divider"></div>
<div class="row">
<div class="col-sm-3">
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#Html.LabelFor(model => model.MiddleName, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.MiddleName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MiddleName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="col-sm-3">
<div class="form-group">
#Html.LabelFor(model => model.Gender, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(x => Model.Gender, new SelectList(Model.Genders, "Value", "Text"), htmlAttributes: new { #class = "form-control", id = "Gender" })
</div>
</div>
</div>
}
if your View is supposed to be for UpdatePatient, then you want to create a model of type RegisterViewModel and add Genders to it, and then pass that model to the View, like this:
public ActionResult UpdatePatient()
{
List<SelectListItem> GenderList = GetGenders();
return View(new RegisterViewModel
{
FirstName = "",
MiddleName = "middle",
LastName = "last",
Genres = GenderList
});
}

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

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

Submitting image path to the database

Im looking enter in some data and then save it into a DB table,The other fields work just fine when submitted to the database. but when it comes to saving the image path it gives null. Ive searched online and everything i find is out of date and doesn't work for the most part.
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Insert([Bind(Include ="id, ImageName, ImageSize")] ImageInfo info, HttpPostedFileBase ImagePath)
{
if(ModelState.IsValid)
{
if (ImagePath != null)
{
var filename = Path.GetFileName(ImagePath.FileName);
var path = Path.Combine(Server.MapPath("~/Uploads"), filename);
ImagePath.SaveAs(path);
ImagePath.SaveAs(HttpContext.Server.MapPath("~/Uploads") + ImagePath.FileName);
info.ImagePath = ImagePath.FileName;
}
db.ImageInfoes.Add(info);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(info);
}
View
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Image</legend>
<div class="editor-label">
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ImageName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ImageName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ImageName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ImageSize, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ImageSize, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ImageSize, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#*#Html.TextBoxFor(model => model.ImagePath, new { type = "file" })*#
<input type="file" name="ImagePath" id="ImagePath" />
#Html.ValidationMessageFor(model => model.ImagePath, "", new { #class = "text-danger" })
</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>
</fieldset>
DB
Any help would be great!.
You want to add enctype="multipart/form-data" to form tag.
I personally like to rename HttpPostedFileBase parameter name to file not to confuse with ImageInfo.ImagePath.
View
#using (Html.BeginForm("Index","Start",FormMethod.Post,new {enctype="multipart/form-data"}))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<fieldset>
<legend>Image</legend>
<div class="editor-label">
<div class="form-horizontal">
<hr/>
...
<div class="form-group">
#* Notice name and id are named as file *#
<input type="file" name="file" id="file"/>
#Html.ValidationMessageFor(model => model.ImagePath, "", new {#class = "text-danger"})
</div>
...
</div>
</div>
</fieldset>
}
Model
public class ImageInfo
{
public string Id { get; set; }
public string ImageName { get; set; }
public string ImageSize { get; set; }
public string ImagePath { get; set; }
}
Action Method
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index([Bind(Include = "id, ImageName, ImageSize")] ImageInfo info,
HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
file.SaveAs(Server.MapPath("~/Uploads") + file.FileName);
info.ImagePath = file.FileName;
}
/*db.ImageInfoes.Add(info);
db.SaveChanges();*/
return RedirectToAction("Index");
}
return View(info);
}

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