CheckBox lists in ASP.NET MVC - c#

I am working on small ticket system for operations maintenance services comp.
Customer open a ticket and gives general information like location,
category description etc.
After technician fix the problem he must give sum details of the
problem from predefined set, use later for statistical reports.
My problem the repair method unable to post updated values to database plus nothing added to Defects_List table.
Note: I used this tutorial as guide
Models:
public partial class Tickets
{
public Tickets()
{
this.DefectsList = new HashSet<Defects_List>();
}
[Key]
[Display(Name = "Ticket Id")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Ticket_Id { get; set; }
[Display(Name = "Project")]
public int Project_Id { get; set; }
[Display(Name = "Issue Date")]
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
public DateTime Issue_Date { get; set; }
[Display(Name = "Category")]
[DisplayFormat(NullDisplayText = "[Not set]")]
public int Category_Id { get; set; }
//Other Properties Removed for clarity
public virtual Business_Category businessCategories { get; set; }
public virtual ICollection<Defects_List> DefectsList { get; set; }
}
public partial class Business_Category
{
public Business_Categories()
{
this.Tickets = new HashSet<Tickets>();
this.Malfunctions = new HashSet<Malfunctions>();
}
[Key]
[Display(Name="Category Id")]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Category_Id { get; set; }
[Display(Name = "Name (eng)")]
[StringLength(60, ErrorMessage = "Name cannot be longer than 60 characters.")]
public string Category_Name { get; set; }
public virtual ICollection<Tickets> Tickets { get; set; }
public virtual ICollection<Manufacturers> Manufacturers { get; set; }
public virtual ICollection<Malfunctions> Malfunctions { get; set; }
}
public partial class Defects_List
{
[Key, Column(Order = 0)]
[Display(Name = "Ticket Id")]
public int Ticket_Id { get; set; }
[Key, Column(Order = 1)]
[Display(Name = "Malfunction Id")]
public int Malfunction_Id { get; set; }
[StringLength(125, ErrorMessage = "Other cannot be longer than 125 characters.")]
public string Other { get; set; }
public virtual ICollection<Tickets> Tickets { get; set; }
public virtual Malfunctions Malfunctions { get; set; }
}
Controller:
// GET: /Tickets/Edit/5
public ActionResult Repair(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var tickets = db.nt_Tickets
.Include(t => t.DefectsList).Where(t => t.Ticket_Id == id)
.Single();
if (tickets == null)
{
return HttpNotFound();
}
PopulateSelectedDefects(tickets);
//Other codes Removed for clarity
return View(tickets);
}
private void PopulateSelectedDefects(nt_Tickets Tickets)
{
int categoryId;
if (Tickets.Category_Id == 2)
categoryId = 1;
else categoryId = Tickets.Category_Id;
var allDefects = (from m in db.sys_Malfunctions
where m.Category_Id == categoryId
select m).ToList();
var ticketDefects = new HashSet<int>(Tickets.DefectsList.Select(t => t.Malfunction_Id));
var viewModel = new List<TicketDefectsViewModel>();
foreach (var defect in allDefects)
{
viewModel.Add(new TicketDefectsViewModel
{
Malfunction_Id = defect.Malfunction_Id,
Malfunction_Name_e = defect.Malfunction_Name_e,
IsSelected = ticketDefects.Contains(defect.Malfunction_Id)
});
}
ViewBag.Defects = viewModel;
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Repair(int? id, string[] selectedDefects)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var ticketToUpdate = db.nt_Tickets
.Include(i => i.DefectsList)
.Where(i => i.Ticket_Id == id)
.Single();
if (TryUpdateModel(ticketToUpdate, "",
new string[] { Ticket_Id,Project_Id,Category_Id,Subject,Workshop_Id,Requested_By,Requestor_Mobile, Requestor_eMail,Location_Id,Ticket_Status,Periority_Id,Assigned_To,Description,Issue_Date,Created_By,Created_Date,Updated_By,Updated_Date" }))
{
ticketToUpdate.Updated_By = User.Identity.Name;
ticketToUpdate.Updated_Date = DateTime.UtcNow;
db.Entry(ticketToUpdate).State = EntityState.Modified;
SetTicketDefects(selectedDefects, ticketToUpdate);
try
{
db.SaveChanges();
return RedirectToAction("Index");
}
catch (DbEntityValidationException dbEx)
{
Exception raise = dbEx;
foreach (var validationErrors in dbEx.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
if (!string.IsNullOrEmpty(message))
ViewBag.errorMessage = message;
}
return View("Error");
}
throw raise;
}
}
PopulateSelectedDefects(ticketToUpdate);
return View("Index");
}
private void SetTicketDefects(string[] selectedDefects, Tickets ticketToUpdate)
{
if (selectedDefects == null)
{
ticketToUpdate.DefectsList = new List<Defects_List>();
return;
}
var selectedDefectsHS = new HashSet<string>(selectedDefects);
var tcketDefects = new HashSet<int>
(ticketToUpdate.DefectsList.Select(c => c.Ticket_Id));
foreach (var defect in db.DefectsLists)
{
if (selectedDefectsHS.Contains(defect.Malfunction_Id.ToString()))
{
if (!tcketDefects.Contains(defect.Malfunction_Id))
{
ticketToUpdate.DefectsList.Add(defect);
}
}
else
{
if (tcketDefects.Contains(defect.Malfunction_Id))
{
ticketToUpdate.DefectsList.Remove(defect);
}
}
}
}
db.DefectsLists here [foreach (var defect in db.DefectsLists)] always empty.
Repair View:
#using (Html.BeginForm("Repair", "Tickets", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
#*#using (Html.BeginForm())*#
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.Ticket_Id)
#Html.HiddenFor(model => model.Issue_Date)
#Html.HiddenFor(model => model.Created_By)
#Html.HiddenFor(model => model.Project_Id)
#Html.HiddenFor(model => model.Created_Date)
<div class="form-group">
#Html.Label("Ticket_Id", new { #class = "control-label col-md-2" })
<div class="col-md-1 " style="margin-top:7px">
#Html.DisplayFor(model => model.Ticket_Id)
</div>
#Html.LabelFor(model => model.Issue_Date, new { #class = "control-label col-md-2" })
<div class="col-md-2" style="margin-top:7px">
#Html.DisplayFor(model => model.Issue_Date, new { #class = "form-control" })
</div>
#Html.LabelFor(model => model.Category_Id, new { #class = "control-label col-md-2" })
<div class="col-md-3" style="margin-top:7px">
#Html.DropDownList("Category_Id", null, new { #class = "form-control", #disabled = "disabled" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Subject, new { #class = "control-label col-md-2" })
<div class="col-md-10" style="margin-top:7px">
#Html.DisplayFor(model => model.Subject, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, new { #class = "control-label col-md-2" })
<div class="col-md-10" style="margin-top:7px">
#Html.DisplayFor(model => model.Description, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Requested_By, new { #class = "control-label col-md-2" })
<div class="col-md-5" style="margin-top:7px">
#Html.DisplayFor(model => model.Requested_By, new { #class = "form-control" })
</div>
#Html.LabelFor(model => model.Requestor_Mobile, new { #class = "control-label col-md-2" })
<div class="col-md-3" style="margin-top:7px">
#Html.DisplayFor(model => model.Requestor_Mobile, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Requestor_eMail, new { #class = "control-label col-md-2" })
<div class="col-md-10" style="margin-top:7px">
#Html.DisplayFor(model => model.Requestor_eMail, new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Ticket_Status, new { #class = "control-label col-md-2" })
<div class="col-md-4" style="margin-top:7px">
#Html.EnumDropDownListFor(model => model.Ticket_Status, new { #class = "form-control" })
</div>
#Html.LabelFor(model => model.Periority_Id, new { #class = "control-label col-md-2" })
<div class="col-md-4" style="margin-top:7px">
#Html.EnumDropDownListFor(model => model.Periority_Id, new { #class = "form-control", #disabled = "disabled" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Location_Id, new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.DropDownList("Location_Id", null, new { #class = "form-control", #disabled = "disabled" })
#Html.ValidationMessageFor(model => model.Location_Id)
</div>
#Html.LabelFor(model => model.Assigned_To, new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.DropDownList("Assigned_To", null, new { #class = "form-control", #disabled = "disabled" })
</div>
</div>
<div class="form-group">
<div class="col-md-10">
#Html.Label("Defects")
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<table class="table table-hover">
<tr>
#{
int cnt = 0;
List<MaintCare.ViewModels.TicketDefectsViewModel> defects = ViewBag.Defects;
foreach (var defect in defects)
{
if (cnt++ % 3 == 0)
{
#:</tr><tr>
}
#:<td>
<input type="checkbox"
name="selectedDefects"
value="#defect.Malfunction_Id"
#(Html.Raw(defect.IsSelected ? "checked=\"checked\"" : "")) />
#defect.Malfunction_Name_e
#:</td>
}
#:</tr>
}
</table>
</div>
</div>
<br />
<div class="form-group">
<div class="col-md-2">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>

Related

The model item passed into the dictionary is of type 'koelkast.Models.ProductsModel

when i tried to submit my edit form i get this issue and i don't know why
productsController edit get
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//ProductsModel productsModel = await db.ProductsModels.FindAsync(id);
var products = await db.ProductsModels.Include(a =>a.categorieId).Include(a => a.users).FirstAsync(a => a.id == id);
if (products == null)
{
return HttpNotFound();
}
var selectedOwnerId = products.users?.Id ?? string.Empty;
var users = db.Users.Select(userItem => new SelectListItem
{
Text = userItem.Email,
Value = userItem.Id,
Selected = userItem.Id == selectedOwnerId
}).ToSafeReadOnlyCollection();
var selectedCategoryId = products.categorieId.id;
var productCategories = db.ProductCategoriesModels
.Select(a => new SelectListItem
{
Value = a.id.ToString(),
Text = a.name,
Selected = a.id == selectedCategoryId
}).ToSafeReadOnlyCollection();
var viewmodel = new productCreatEditViewModel()
{
Products = products,
productCategories = productCategories,
users = users
};
//ViewBag.users = userList;
//ViewBag.productcategorieId = new SelectList(db.ProductCategoriesModels, "id", "Name", productsModel.productcategorieId);
return View(viewmodel);
}
productsController edit post
// POST: Products/Edit/5
// To protect from overposting attacks, enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Edit([Bind(Include = "id,name,calorie,price,productcategorieId,userId")] ProductsModel productsModel)
{
if (ModelState.IsValid)
{
db.Entry(productsModel).State = EntityState.Modified;
await db.SaveChangesAsync();
return RedirectToAction("Index");
}
ViewBag.productcategorieId = new SelectList(db.ProductCategoriesModels, "id", "Name", productsModel.productcategorieId);
return View(productsModel);
}
edit view
#model koelkast.ViewModels.productCreatEditViewModel
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ProductsModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Products.id)
<div class="form-group">
#Html.LabelFor(model => model.Products.name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Products.name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Products.name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Products.calorie, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Products.calorie, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Products.calorie, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Products.price, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Products.price, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Products.price, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Products.categorieId.name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => Model.Products.categorieId.id,Model.productCategories, new { Name = "productCategoriesId", #class ="form-control"})
#Html.ValidationMessageFor(model => model.productCategories, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Products.users.Email, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => Model.Products.users.Id,Model.users, new {Name = "UserId", #class = "form-control" })
#Html.ValidationMessageFor(model => model.Products.users.Email, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
ViewModel
The model item passed into the dictionary is of type 'koelkast.Models.ProductsModel', but this dictionary requires a model item of type 'koelkast.ViewModels.productCreatEditViewModel'.
namespace koelkast.ViewModels
{
public class productCreatEditViewModel
{
[Required]
public ProductsModel Products { get; set; }
[Required]
public ICollection<SelectListItem> productCategories { get; set; }
[Required]
public ICollection<SelectListItem> users { get; set; }
}
}
productModel
namespace koelkast.Models
{
public class ProductsModel
{
[Key]
public int id { get; set; }
[Required,Display(Name = "name")]
public string name { get; set; }
//display name is de naam die hij gaat laten zien als nnaam in je view
[Required, Display(Name = "calorie")]
public int calorie { get; set; }
[Required, Display(Name = "price")]
public float price { get; set; }
[Display(Name = "categories")]
//hier zet je die foreing key
//zoals je kunt zien roep ik alleen de model aan
public int? productcategorieId { get; set; }
[ForeignKey("productcategorieId")]
public virtual ProductCategoriesModel categorieId { get; set; }
//je zegt hier dus dat dit de Id is(userId)
//van applicationUser table users
public string UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser users { get; set; }
}
}
https://i.stack.imgur.com/Qaq67.png
you have a bug here, fix it
public async Task<ActionResult> Edit(ProductsModel productsModel)
{
}
you have 2 choices
1.Change ProductsModel to ProductCreatEditViewModel
or
Return ProductCreatEditViewModel as model
var viewmodel = new productCreatEditViewModel()
{
Products = productsModel,
productCategories = productCategories,
users = users
};
return View(viewModel);

MVC - Update Value in Database Table

I have been trying to come up with a solution for quite some time now but they all seem to fail.
I have two tables -> AssignedRoles & Incidence. Within the "Assignedroles" there is a "Status" Column that is auto-assigned "A" upon creation of data.
Given the nature of my program, i would like to change this value from "A" to "C" but from the "Incidence" Controller on the Edit Method.
Below is what i have tried.
public async Task<ActionResult> Edit(Incidence incidence, AssignedRoles assignedRoles)
{
if (ModelState.IsValid)
{
assignedRoles.Status = "C";
DB.Entry(incidence).State = EntityState.Modified;
DB.AssignedRoles.Add(assignedRoles);
UpdateModel(assignedRoles);
await DB.SaveChangesAsync();
return RedirectToAction("Dashboard");
}
return View(incidence);
}
The View Controller below displays Incidences allocated to the specific admin
The Members() contains the View from LoadUsersData()
public ActionResult Members()
{
return View();
}
public ActionResult LoadUsersData()
{
try
{
var draw = Request.Form.GetValues("draw").FirstOrDefault();
var start = Request.Form.GetValues("start").FirstOrDefault();
var length = Request.Form.GetValues("length").FirstOrDefault();
var sortColumn = Request.Form.GetValues("columns[" + Request.Form.GetValues("order[0][column]").FirstOrDefault() + "][name]").FirstOrDefault();
var sortColumnDir = Request.Form.GetValues("order[0][dir]").FirstOrDefault();
var searchValue = Request.Form.GetValues("search[value]").FirstOrDefault();
int pageSize = length != null ? Convert.ToInt32(length) : 0;
int skip = start != null ? Convert.ToInt32(start) : 0;
int recordsTotal = 0;
var adminUserID = Convert.ToInt32(Session["AdminUser"]);
var rolesData = _IUsers.ShowallUsersUnderAdmin(sortColumn, sortColumnDir, searchValue, adminUserID);
recordsTotal = rolesData.Count();
var data = rolesData.Skip(skip).Take(pageSize).ToList();
return Json(new { draw = draw, recordsFiltered = recordsTotal, recordsTotal, data = data });
}
catch (Exception)
{
throw;
}
}
The Edit Controller
[HttpGet]
public async Task<ActionResult> Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Incidence incidence = await DB.Incidences.FindAsync(id);
if (incidence == null)
{
return HttpNotFound();
}
return View(incidence);
}
Incidence Model
public class Incidence
{
[Key]
public int RegistrationID { get; set; }
[Required]
public string Name { get; set; }
[Required]
[MaxLength(7)]
public string TSCNO { get; set; }
public string General { get; set; }
public string Location { get; set; }
[Required]
[DataType(DataType.PhoneNumber)]
public string Cell { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[DataType(DataType.MultilineText)]
public string Issue { get; set; }
public int? RoleID { get; set; }
[DataType(DataType.MultilineText)]
[MinLength(5,ErrorMessage ="Provide Valid Feedback")]
public string FeedBack { get; set; }
}
AssignedRoles Model
public class AssignedRoles
{
[Key]
public int AssignedRolesID { get; set; }
public int? AssignToAdmin { get; set; }
public int? CreatedBy { get; set; }
public DateTime? CreatedOn { get; set; }
public int RegistrationID { get; set; }
public string Status { get; set; }
}
Incidence Edit View
#model CallCentre.Models.Incidence
#{
ViewBag.Title = "Edit";
Layout = "~/Views/Shared/AdminLTE.cshtml";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.RegistrationID)
<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.TSCNO, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TSCNO, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TSCNO, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.General, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.General, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.General, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Location, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Location, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Location, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Cell, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Cell, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Cell, "", 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.Issue, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Issue, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Issue, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FeedBack, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FeedBack, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FeedBack, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
Modify your edit action to the code below.
// remove assignedRoles object on the parameter, we only need incidence
public async Task<ActionResult> Edit(Incidence incidence)
{
if (ModelState.IsValid)
{
// we need to select the assignedRole from that RegistrationId
var role = db.AssignedRoles.FirstOrDefault(a=>a.RegistrationID == incidence.RegistrationID)
role.Status = "C";
DB.Entry(incidence).State = EntityState.Modified;
// you're just editing the assignedRole right? no need to add a new one. Comment out or remove the code below
// DB.AssignedRoles.Add(assignedRoles);
// UpdateModel(assignedRoles);
await DB.SaveChangesAsync();
return RedirectToAction("Dashboard");
}
return View(incidence);
}

The INSERT statement conflicted with the FOREIGN KEY constraint dropdownlist [duplicate]

This question already has answers here:
What Causes The INSERT statement conflicted with the FOREIGN KEY constraint?
(2 answers)
Closed 6 years ago.
I'm working in ASP.NET MVC Web Application, so I want to insert values from another table (I get it with dropdownlist), but when I try to post, I get this:
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_dbo.Products_dbo.Subcategories_SubcategoryId". The conflict
occurred in database "ProyectName", table "dbo.Subcategories", column
'SubcategoryId'. The statement has been terminated.
Products model:
public class Product
{
public int ProductId { get; set; }
public int SubcategoryId { get; set; }
public virtual Subcategory Subcategory { get; set; }
public string Name { get; set; }
public string Presentation { get; set; }
public string Image { get; set; }
public string Alt { get; set; }
public bool IsDeleted { get; set; }
Product ViewModel
public class ProductViewModel
{
public string Name { get; set; }
public string Presentation { get; set; }
public string Image { get; set; }
public string Alt { get; set; }
public int SelectedSubcategory { get; set; }
public IEnumerable <SelectListItem> Subcategory { get; set; }
}
Subcategory Model:
public class Subcategory
{
public int SubcategoryId { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Image { get; set; }
public string Alt { get; set; }
public string Pdf { get; set; }
public bool IsDeleted { get; set; }
public bool IsInstalled { get; set; }
}
Get Controller
public ActionResult Create()
{
var subcategoryList = new ProductViewModel
{
Subcategory = new SelectList(db.SubcategoriesList, "SubcategoryId", "Name")
};
return View(subcategoryList);
}
Post Controller(Service method):
public class ProductService : IProductService
{
private EfDatabase db = new EfDatabase();
public async Task<string> CreateProduct(ProductViewModel model)
{
var product = new Product
{
Name = model.Name,
Presentation = model.Presentation,
Image = model.Image,
Alt = model.Alt,
SubcategoryId = model.SelectedSubcategory,
IsDeleted = false
};
db.ProductsList.Add(product);
await db.SaveChangesAsync();
return "Product " + model.Name + "has been created";
View:
#model Proyect.Models.ViewModels.ProductViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Product</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.SubcategoryId, "SubcategoryId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(m => m.SelectedSubcategory, Model.Subcategory, "-Selecciona una opcion-", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.SelectedSubcategory)
</div>
</div>
<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.Presentation, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Presentation, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Presentation, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Image, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Image, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Image, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Alt, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Alt, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Alt, "", 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>
So I don't found any error on my code, what's wrong with that? can any one help me to solve this problem?
My question is unique because model.SelectedSubcategory don't get Id value from another table, It always get 0 so in the other questions no make any comparision with that
Thankyou in advance!
MY CREATE VIEW NOW
#model myPROYECT.Models.ViewModels.ProductViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Product</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="col-md-10">
#Html.DropDownListFor(m => m.SelectedSubcategory, Model.Subcategory, "-Selecciona una opcion-", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.SelectedSubcategory)
</div>
</div>
<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.Presentation, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Presentation, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Presentation, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Image, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Image, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Image, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Alt, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Alt, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Alt, "", 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>
There's nothing that requires a Subcategory to be selected. You're likely to get this error when a selection hasn't been made for subcategory. You should make subcategory required or make null a value that's possible to get back.
public class Product
{
public int ProductId { get; set; }
public int? SubcategoryId { get; set; }
public virtual Subcategory Subcategory { get; set; }
public string Name { get; set; }
public string Presentation { get; set; }
public string Image { get; set; }
public string Alt { get; set; }
public bool IsDeleted { get; set; }
}
using System.ComponentModel.DataAnnotations;
public class ProductViewModel
{
public int? SubcategoryId { get; set; }
public string Name { get; set; }
public string Presentation { get; set; }
public string Image { get; set; }
public string Alt { get; set; }
[Required]
public int? SelectedSubcategory { get; set; }
public IEnumerable Subcategory { get; set; }
}
Post Controller(Service method):
public class ProductService : IProductService
{
private EfDatabase db = new EfDatabase();
public async Task<string> CreateProduct(ProductViewModel model)
{
if (!ModelState.IsValid)
return View("Create");
var product = new Product
{
Name = model.Name,
Presentation = model.Presentation,
Image = model.Image,
Alt = model.Alt,
SubcategoryId = model.SelectedSubcategory,
IsDeleted = false
};
db.ProductsList.Add(product);
await db.SaveChangesAsync();
return "Product " + model.Name + "has been created";
}
}

System.ArgumentNullException' occurred in System.Core.dll but was not handled in user code [duplicate]

This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 6 years ago.
Net I was trying to do a Edit for uploading a image but now whenever I edit it crashes and gives 'System.ArgumentNullException' occurred in System.Core.dll but was not handled in user code'. This all started when I tried to implement an edit for the image upload. It crashes on the edit.cshtml page, I have placed a comment right where it crashes. Any help would be really appreciated, if you require any more information please let me know
AnimalsController
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "LatinNameID,CommonNameID,LatinName,CommonName,GenusID,SpeciesID,Description,FamilyID,CountryID,ContinentID,OrderID")] Animal animal, HttpPostedFileBase upload,string latinID,string commonID)
{
var animalToUpdate = db.Animals.Find(latinID,commonID);
//Does a check to see if entry exists in database
if ((db.Animals.Any(ac => ac.LatinName.Equals(animal.LatinName))) || (db.Animals.Any(ac => ac.CommonName.Equals(animal.CommonName))))
{
ModelState.AddModelError("LatinName", "Already Exists");
ModelState.AddModelError("CommonName", "Duplicate Entry");
}
else
{
if (ModelState.IsValid)
{
if (upload != null && upload.ContentLength > 0)
{
if (animalToUpdate.Files.Any(f => f.FileType == FileType.Avatar))
{
db.File.Remove(animalToUpdate.Files.First(f => f.FileType == FileType.Avatar));
}
var avatar = new File
{
FileName = System.IO.Path.GetFileName(upload.FileName),
FileType = FileType.Avatar,
ContentType = upload.ContentType
};
using (var reader = new System.IO.BinaryReader(upload.InputStream))
{
avatar.Content = reader.ReadBytes(upload.ContentLength);
}
animalToUpdate.Files = new List<File> { avatar };
}
db.Entry(animal).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
ViewBag.ContinentID = new SelectList(db.Continents, "ContinentID", "ContinentName", animal.ContinentID);
ViewBag.CountryID = new SelectList(db.Countries, "CountryID", "CountryName", animal.CountryID);
ViewBag.FamilyID = new SelectList(db.Families, "FamilyID", "FamilyName", animal.FamilyID);
ViewBag.GenusID = new SelectList(db.Genus, "GenusID", "GenusName", animal.GenusID);
ViewBag.OrderID = new SelectList(db.Orders, "OrderID", "OrderName", animal.OrderID);
ViewBag.SpeciesID = new SelectList(db.Species, "SpeciesID", "SpeciesName", animal.SpeciesID);
return View(animal);
}
Edit View
<h2>Edit</h2>
#using (Html.BeginForm("Edit", "Animals", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Animal</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.LatinNameID)
#Html.HiddenFor(model => model.CommonNameID)
<div class="form-group">
#Html.LabelFor(model => model.LatinName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LatinName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LatinName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CommonName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CommonName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CommonName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.GenusID, "GenusID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("GenusID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.GenusID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SpeciesID, "SpeciesID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("SpeciesID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.SpeciesID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Description, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Description, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Description, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FamilyID, "FamilyID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("FamilyID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.FamilyID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CountryID, "CountryID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("CountryID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CountryID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ContinentID, "ContinentID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ContinentID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ContinentID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OrderID, "OrderID", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("OrderID", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.OrderID, "", new { #class = "text-danger" })
</div>
</div>
//Crashes here
#if (Model.Files.Any(f => f.FileType == FileType.Avatar))
{
<div class="form-group">
<span class="control-label col-md-2"><strong>Current Avatar</strong></span>
<div class="col-md-10">
<img src="~/File?id=#Model.Files.First(f => f.FileType == FileType.Avatar).FileId" alt="avatar" />
</div>
</div>
}
<div class="form-group">
#Html.Label("Avatar", new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" id="Avatar" name="upload" />
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Save" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Model
//Animal
public class Animal
{
[Key, Column(Order = 0)]
public string LatinNameID { get; set; }
public string LatinName { get; set; }
[Key, Column(Order = 1)]
public string CommonNameID { get; set; }
public string CommonName { get; set; }
public string GenusID { get; set; }
public string SpeciesID { get; set; }
public string Description { get; set; }
public string FamilyID { get; set; }
public string CountryID { get; set; }
public string ContinentID { get; set; }
public string OrderID { get; set; }
public virtual Continent Continent { get; set; }
public virtual Genus Genus { get; set; }
public virtual Species Species { get; set; }
public virtual Family Family { get; set; }
public virtual Country Country { get; set; }
public virtual Order Order { get; set; }
public virtual ICollection<File> Files { get; set; }
}
//File
public class File
{
public int FileId { get; set; }
[StringLength(255)]
public string FileName { get; set; }
[StringLength(100)]
public string ContentType { get; set; }
public byte[] Content { get; set; }
public FileType FileType { get; set; }
public string LatinNameID { get; set; }
public string CommonNameID { get; set; }
public virtual Animal Animal { get; set; }
}
The error that you are getting suggests that you are calling a method with a null argument somewhere in your code. Since it crashes with the if statement beginning with Model.Files.Any(f => f.FileType == FileType.Avatar), I would verify that Model.Files is not null before proceeding.
The code could look like the following:
#if (Model.Files != null && Model.Files.Any(f => f.FileType == FileType.Avatar))
{
<div class="form-group">
<span class="control-label col-md-2"><strong>Current Avatar</strong></span>
<div class="col-md-10">
<img src="~/File?id=#Model.Files.First(f => f.FileType == FileType.Avatar).FileId" alt="avatar" />
</div>
</div>
}
If Model.Files should never be null, then you might need to investigate why that value is not being set as well.

How to Modify MVC models to use nested Subcategories

I have a working MVC 5 app we use for classroom supplies with a simple welcome page that shows all categories along the left side of the page and a partial view that displays all subcategories for any category that is clicked.
Click any subcategory and the view updates with all products that match the subcategory.
It's worked fine for quite some time but now I need to add a third nested subcategory so my subcategories can have a subcategory nested below it like this:
(1)Category (2)---Subcategory (3)------Subcategory
or
(1)Art Supplies (catgory) (2)---Crayons (subcategory) (2)---Paper (subcategory) (3)------Construction (sub-subcategory) (3)------Plain (sub-subcategory) (3)------Etching (sub subcategory)
I can't get my models updated correctly to produce what I need. I can't work out the proper way to add that third nested subcateory to our models. I've spent a few days trying and just can't determine the correct way to do it.
I've tried a "flat" single model with parentID, Parent Category, but can't get the create and edit pages to display drop-downs like our models below produce.
Being able to utilize drop-down menus on our create and edit pages are a plus as we have young students who use the app and it's simpler for them.
And I'd like to use the same to update our public view.
I know if I get the models correct then I can translate that to my views as needed. If anyone can help with the proper structure it would be very much appreciated.
Below are our models:
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public virtual ICollection<SubCategory> SubCategories { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
public class SubCategory
{
public int SubCategoryId { get; set; }
public string SubCategoryName { get; set; }
public int CategoryId { get; set; }
public virtual Category Category { get; set; }
public virtual ICollection<Product> Products { get; set; }
}
public class Product
{
[HiddenInput(DisplayValue = false)]
public int ProductId { get; set; }
public string ProductName { get; set; }
public int ProductNumber { get; set; }
public string UnitOfMeasure { get; set; }
public string ProductDescription { get; set; }
public decimal Price { get; set; }
public int CategoryId { get; set; }
public int SubCategoryId { get; set; }
public virtual Category Category { get; set; }
public virtual SubCategory SubCategory { get; set; }
}
Here is our controller for our create action:
public class ProductsController : Controller
{
private EFDbContext db = new EFDbContext();
public ActionResult Create()
{
var catid = 1;
try
{
catid = (from c in db.Categories select c).FirstOrDefault().CategoryId;
}
catch (Exception)
{
catid = 1;
}
ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "CategoryName", catid);
var subcategories = (from sub in db.SubCategories where sub.CategoryId == catid select new { sub.SubCategoryId, sub.SubCategoryName }).ToList();
ViewBag.SubCategoryId = new SelectList(subcategories, "SubCategoryId", "SubCategoryName");
return View();
}
// POST: Products/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ProductId,ProductName,ProductNumber,UnitOfMeasure,ProductDescription,Price,CategoryId,SubCategoryId")] Product product)
{
var subcatcheck = (from sub in db.SubCategories where sub.CategoryId == product.CategoryId && sub.SubCategoryId == product.SubCategoryId select new { sub.SubCategoryId, sub.SubCategoryName }).ToList();
if (ModelState.IsValid && product.ProductName != null && product.CategoryId != 0 && product.SubCategoryId != 0 && subcatcheck.Count != 0)
{
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.CategoryId = new SelectList(db.Categories, "CategoryId", "CategoryName", product.CategoryId);
//ViewBag.SubCategoryId = new SelectList(db.SubCategories, "SubCategoryId", "SubCategoryName", product.SubCategoryId);
var subcategories = (from sub in db.SubCategories where sub.CategoryId == product.CategoryId select new { sub.SubCategoryId, sub.SubCategoryName }).ToList();
ViewBag.SubCategoryId = new SelectList(subcategories, "SubCategoryId", "SubCategoryName");
return View(product);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
And lastly our create view
#model 3rd6thgrade.Domain.Entities.Product
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Product</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ProductName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ProductName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ProductNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.UnitOfMeasure, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UnitOfMeasure, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UnitOfMeasure, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ProductDescription, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ProductDescription, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductDescription, "", 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">
#Html.LabelFor(model => model.CategoryId, "CategoryId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownList("CategoryId", null, htmlAttributes: new { #class = "form-control" })*#
#Html.DropDownList("CategoryId", null, new {onchange = "this.form.submit(0)", #class = "form-control"})
#Html.ValidationMessageFor(model => model.CategoryId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SubCategoryId, "SubCategoryId", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("SubCategoryId", null, htmlAttributes: new { #class = "form-control" })
#* #Html.DropDownList("SubCategoryId", null, new { onchange = "this.form.submit(0)", #class = "form-control" })*#
#Html.ValidationMessageFor(model => model.SubCategoryId, "", 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>

Categories

Resources