MVC- populate dropdownlist depend on another selection - asp.net-mvc

I've three dropdownlists each depend on the previous selection (stocks ,category,items) .
each dropdownlist populated by Viewbag from controller
controller:
ViewBag.stock_id = new SelectList(db.stocks, "stock_id", "stock_name");
ViewBag.cat_id = new SelectList(db.categories, "cat_id", "cat_name");
ViewBag.item_id = new SelectList(db.items, "item_id", "item_name");
[HttpGet]
public ActionResult UpdateitemDrop1(int stock_id)
{
var fromDatabaseEF = new SelectList(db.categories.Where(x => x.stock_id == stock_id).ToList(), "cat_id", "cat_name");
SelectList vb = fromDatabaseEF;
return Json(vb, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult UpdateitemDrop2(int cat_id)
{
SelectList data= new SelectList(db.items.Where(x => x.cat_id == cat_id).ToList(), "item_id", "item_name");
return Json(data, JsonRequestBehavior.AllowGet);
}
view:
<div class="form-group">
#Html.LabelFor(model => model.stock_id, "stock_id", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("stock_id", null, htmlAttributes: new { #class = "form-control", #id = "stock_id" })
#Html.ValidationMessageFor(model => model.employee_id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.cat_id, "cat_id", htmlAttributes: new { #class = "control-label col-md-2"})
<div class="col-md-10">
#Html.DropDownList("cat_id", null, htmlAttributes: new { #class = "form-control", #id = "cat_id", disabled = "disabled" })
#Html.ValidationMessageFor(model => model.employee_id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.item_id, "item_id", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("item_id", null, htmlAttributes: new { #class = "form-control", #id = "item_id" , disabled = "disabled" })
#Html.ValidationMessageFor(model => model.item_id, "", new { #class = "text-danger" })
</div>
</div>
<script>
$(function () {
$('#stock_id').change(function () {
var select = $('#cat_id');
var stockV = $("#stock_id :selected").val();
alert();
$.ajax({
url: '/additions/UpdateitemDrop1',
type: "GET",
dataType: "JSON",
data: { stock_id: stockV },
success: function (vb) {
select.empty();
$(vb).each(function () {
select.add($("<option></option>").val(vb.cat_id).html(vb.cat_name));
});
}
});
});
$('#cat_id').change(function () {
var catV = $("#cat_id :selected").val();
$('#item_id').prop("disabled", false);
alert();
$.ajax({
url: '/additions/UpdateitemDrop2',
type: "GET",
dataType: "JSON",
data: { item_id: catV },
success: function () {
$("#item_id").html("");
$("#item_id").empty();
$.each(data, function (i, items) {
$("#item_id").append(
$('<option></option>').val(items.item_id).html(items.item_name));
});
}
});
});
});
</script>
but when I select option from first dropdownlist (stock_id) ,it stops at "empty()" function and doesn't populate the second dropdownlist
any help please?

This will help.
Controller - I am starting on Index16.
public class Stock
{
public string Id { get; set; } //value
public string Name { get; set; } //text
}
public class Category
{
public string Id { get; set; }
public string Name { get; set; }
}
public class Item
{
public string Id { get; set; }
public string Name { get; set; }
}
public class ViewModel
{
public IList<Stock> StockList { get; set; }
public IList<Category> CategoryList { get; set; }
public IList<Item> ItemList { get; set; }
public string SelectedStock { get; set; }
public string SelectedCategory { get; set; }
public string SelectedItem { get; set; }
}
public class HomeController : Controller
{
[HttpGet]
public ActionResult UpdateitemDrop1(string stock_id)
{
List<Stock> stocks;
List<Category> categories;
List<Item> items;
PopulateViewBags(out stocks, out categories, out items);
var q = categories.Where(x => x.Id == stock_id).ToArray();
return Json(q, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult UpdateitemDrop2(string cat_id)
{
List<Stock> stocks;
List<Category> categories;
List<Item> items;
PopulateViewBags(out stocks, out categories, out items);
ViewBag.item_id = new SelectList(items.Where(x => x.Id == cat_id));
return Json(ViewBag.item_id, JsonRequestBehavior.AllowGet);
}
public ActionResult Index16()
{
List<Stock> stocks;
List<Category> categories;
List<Item> items;
PopulateViewBags(out stocks, out categories, out items);
var viewModel = new ViewModel { CategoryList = categories, ItemList = items, StockList = stocks };
return View(viewModel);
}
private void PopulateViewBags(out List<Stock> stocks, out List<Category> categories, out List<Item> items)
{
stocks = new List<Stock> {
new Stock { Id = "1", Name = "Stock1"},
new Stock { Id = "2", Name = "Stock2"},
new Stock { Id = "3", Name = "Stock3"}
};
categories = new List<Category> {
new Category { Id = "1", Name = "Category1"},
new Category { Id = "2", Name = "Category2"},
new Category { Id = "3", Name = "Category3"}
};
items = new List<Item> {
new Item { Id = "1", Name = "Item1"},
new Item { Id = "2", Name = "Item2"},
new Item { Id = "3", Name = "Item3"}
};
ViewBag.cat_id = new SelectList(categories, "Id", "Name");
ViewBag.item_id = new SelectList(items, "Id", "Name");
ViewBag.stock_id = new SelectList(stocks, "Id", "Name");
}
View
#model WebApplication2.Controllers.ViewModel
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index16</title>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script>
$(function () {
$('#stock_id').change(function () {
var stockV = $("#stock_id :selected").val();
$.ajax({
url: '/home/UpdateitemDrop1',
type: "GET",
//dataType: "JSON",
data: { stock_id: stockV },
success: function (data) {
alert(data[0].Id);
alert(data[0].Name)
$("#cat_id").html("");
$.each(data, function (i, category) {
$("#cat_id").append(
$('<option></option>').val(category.Id).html(category.Name));
})
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
$('#cat_id').change(function () {
alert("category id changed");
//var catV = $("#cat_id :selected").val();
//alert();
//$.ajax({
// url: '/additions/UpdateitemDrop2',
// type: "GET",
// dataType: "JSON",
// data: { item_id: catV },
// success: function () {
// $("#item_id").html("");
// $.each(data, function (i, items) {
// $("#item_id").append(
// $('<option></option>').val(items.item_id).html(items.item_name));
// });
// }
//});
});
});
</script>
</head>
<body>
<div class="form-group">
<div class="col-md-10">
#Html.LabelFor(model => model.StockList[0].Name, "stock_id", htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.SelectedStock, ViewBag.stock_id as SelectList,
"Select Stock", new { #class = "form-control", #id = "stock_id" })
#Html.ValidationMessageFor(model => model.SelectedStock, "", new { #class = "text-danger" })
#Html.LabelFor(model => model.CategoryList[0].Name, "cat_id", htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.SelectedCategory, ViewBag.cat_id as SelectList,
"Select Category", new { #class = "form-control", #id = "cat_id" })
#Html.ValidationMessageFor(model => model.SelectedCategory, "", new { #class = "text-danger" })
#Html.LabelFor(model => model.ItemList[0].Name, "item_id", htmlAttributes: new { #class = "control-label col-md-2" })
#Html.DropDownListFor(model => model.SelectedItem, ViewBag.item_id as SelectList,
"Select Item", new { #class = "form-control", #id = "item_id" })
#Html.ValidationMessageFor(model => model.SelectedItem, "", new { #class = "text-danger" })
</div>
</div>
</body>
</html>

Related

System.InvalidOperationException: 'The ViewData item that has the key 'X is of type 'System.Int32' but must be of type 'IEnumerable<SelectListItem>'.'

I got this error when I want to Create my Contact. Need help I would be thankful.
My database SQL database table is connected via entity framework.
Home Controller / Create Action
[HttpGet]
public ActionResult Create()
{
List<Country> CountryList = db.Countries.ToList();
ViewBag.CountryList = new SelectList(CountryList, "CountryId", "CountryName");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(CountryStateContactViewModel csvm)
{
if (!ModelState.IsValid)
{
return View(csvm);
}
Contact model = new Contact()
{
CountryId = csvm.CountryId,
StateId = csvm.StateId,
ContactId = csvm.ContactId,
ImeOsobe = csvm.ImeOsobe
...and all other fields
};
db.Contacts.Add(model);
try
{
db.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException db)
{
Exception raise = db;
foreach (var validationErrors in db.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
string message = string.Format("{0}:{1}",
validationErrors.Entry.Entity.ToString(),
validationError.ErrorMessage);
raise = new InvalidOperationException(message, raise);
}
}
throw raise;
}
return RedirectToAction("Index");
}
Now here is ViewModel
public int CountryId { get; set; }
[Required]
[Display(Name = "Naziv županije")]
public string CountryName { get; set; }
public int StateId { get; set; }
[Required]
[Display(Name = "Naziv općine")]
public string StateName { get; set; }
public int ContactId { get; set; }
public virtual Country Country { get; set; }
public virtual State State { get; set; }
....and all other fields
And finally here is "Create" view.
#model AkvizicijeApp_4_7.Models.CountryStateContactViewModel
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.CountryId, htmlAttributes: new { #class = "control-label col-md-2"
})
<div class="col-md-10">
#Html.DropDownListFor(model => model.CountryId, ViewBag.CountryList as SelectList, "--Select
Country--", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CountryId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StateId, htmlAttributes: new { #class = "control-label col-md-2"
})
<div class="col-md-10">
#Html.DropDownListFor(model => model.StateId, new SelectList(" "), "--Select State--", new {
#class = "form-control" })
#Html.ValidationMessageFor(model => model.StateId, "", new { #class = "text-danger" })
</div>
</div>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>CountryStateContactViewModel</h4>
<hr />
<div class="form-group">
#Html.LabelFor(model => model.ContactId, htmlAttributes: new { #class = "control-label
col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ContactId, new { htmlAttributes = new { #class =
"form-control" } })
#Html.ValidationMessageFor(model => model.ContactId, "", new { #class = "text-danger"
})
</div>
</div>
And after that is all other fields and js for parent/child dropdown list.
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script>
$(document).ready(function () {
$("#CountryId").change(function () {
$.get("/Home/GetStateList", { CountryId: $("#CountryId").val() }, function (data) {
$("#StateId").empty();
$.each(data, function (index, row) {
$("#StateId").append("<option value='" + row.StateId + "'>" + row.StateName + "
</option>")
});
});
})
});
</script>
Please help me solve my problem. <3

How to store and display SelectList data

I am using SelectList to populate dropdownlists in my view. It works for the Create and Edit views to store ID value data in a table. How do I retrieve the 'Name' value to display in a Details view?
Model
Public Class Employee {
[Key]
public int ID { get; set;}
public string UserName {get; set; }
public byte Gender { get; set; }
}
ViewModel
public class EmployeeEditViewModel {
public int ID { get; set; }
public string UserName { get; set; }
public SelectList GenderList { get; set; }
public EmployeeEditViewModel () {
GenderList = CommonHelper.GenderList(null);
}
}
Helper
public static SelectList GenderList(object selected)
{
return new SelectList(new[]
{
new { Value = 0, Name = "Male" },
new { Value = 1, Name = "Female" }
}
, "Value", "Name", selected);
}
Edit View
#model Models.ViewModel.EmployeeEditViewModel
#using (Html.BeginForm()) {
#Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.UserName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.UserName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.UserName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.GenderList, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Gender, Model.GenderList, "- Select -", new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.GenderList, "", new { #class = "text-danger" })
</div>
</div>
}
Controller
[HttpPost]
public ActionResult CreateEmployee(EmployeeEditViewModel emProfile)
{
try
{
if (ModelState.IsValid)
{
Employee newUser = new Employee();
newUser.UserName = emProfile.UserName;
newUser.Gender = emProfile.Gender;
userRepository.Add(newUser);
userRepository.SaveChanges();
return RedirectToAction("Index");
}
}
catch (Exception ex)
{ }
return View(emProfile);
}
So far it works great, I am able to create, edit Employee records and 1 or 0 is stored in the table for the gender.
But when I want to display the employee data in a details view how do I get the text 'Male' or 'Female'?
I ended up creating a helper method to retrieve the text.
public static string GetTextFromSelectList(int id, string listName)
{
string selectedText = string.Empty;
SelectListItem selectedItem;
switch (listName)
{
case "Gender":
selectedItem = Helper.CommonHelper.GenderList(null).FirstOrDefault(x => x.Value == id.ToString());
selectedText = selectedItem == null ? null : selectedItem.Text;
break;
default:
selectedText = null;
break;
}
return selectedText;
}

MVC File Upload - Saving path and filename back to database

Not sure where the issue is - the file upload is working fine and going to the correct folder however the path and filename are not being stored in the database.
I want to use this so that I can add links to my index view for each document uploaded.
Any help on this would be brilliant as I have been racking my brains for 2 days over this.
Regards
Andy
Model:
namespace inventIT.Models
{
using System;
using System.Collections.Generic;
public partial class ComputerInventory
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public ComputerInventory()
{
this.ComputerInstallations = new HashSet<ComputerInstallation>();
}
public int RecordID { get; set; }
public string ComputerAdName { get; set; }
public string ComputerBrand { get; set; }
public string ComputerModel { get; set; }
public string ComputerSerialNumber { get; set; }
public string ComputerOS { get; set; }
public System.DateTime ComputerPurchaseDate { get; set; }
public string ComputerAddedBy { get; set; }
public Nullable<bool> ComputerArchived { get; set; }
public Nullable<System.DateTime> ComputerArchivedDate { get; set; }
public string FileDesc { get; set; }
public string FileName { get; set; }
public string Extension { get; set; }
public Nullable<int> FileID { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<ComputerInstallation> ComputerInstallations { get; set; }
public virtual Lookup Lookup { get; set; }
public virtual Lookup Lookup1 { get; set; }
public virtual ITTeamLookup ITTeamLookup { get; set; }
public virtual Lookup Lookup2 { get; set; }
}
}
Controller:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using inventIT.Models;
namespace inventIT.Controllers
{
public class ComputerInventoriesController : Controller
{
private HAWKTRAINING_INVENTITEntities db = new HAWKTRAINING_INVENTITEntities();
// GET: ComputerInventories
public ViewResult Index(string sortOrder, string currentFilter, string searchString, int? page, int? PageSize)
{
ViewBag.searchString = "";
ViewBag.CurrentSort = sortOrder;
ViewBag.NameSortParm = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewBag.DateSortParm = sortOrder == "Date" ? "date_desc" : "Date";
if (searchString != null)
{
page = 1;
}
else
{
searchString = currentFilter;
}
ViewBag.CurrentFilter = searchString;
var AssessorIDs = from s in db.ComputerInventories
select s;
if (!String.IsNullOrEmpty(searchString))
{
AssessorIDs = AssessorIDs.Where(s => s.ComputerAdName.Contains(searchString) || searchString == null || searchString == "");
}
switch (sortOrder)
{
case "name_desc":
AssessorIDs = AssessorIDs.OrderByDescending(s => s.ComputerAdName);
break;
case "Date":
AssessorIDs = AssessorIDs.OrderBy(s => s.ComputerPurchaseDate);
break;
case "date_desc":
AssessorIDs = AssessorIDs.OrderByDescending(s => s.ComputerPurchaseDate);
break;
default: // Name ascending
AssessorIDs = AssessorIDs.OrderBy(s => s.ComputerAdName);
break;
}
var computerInventories = db.ComputerInventories.Include(c => c.Lookup).Include(c => c.Lookup1).Include(c => c.ITTeamLookup).Include(c => c.Lookup2);
return View(computerInventories.Where(s => s.ComputerAdName.Contains(searchString) || searchString == null || searchString == "").OrderByDescending(c => c.ComputerAdName).ToList());
}
// GET: ComputerInventories/Details/5
public ActionResult Details(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ComputerInventory computerInventory = db.ComputerInventories.Find(id);
if (computerInventory == null)
{
return HttpNotFound();
}
return View(computerInventory);
}
// GET: ComputerInventories/Create
public ActionResult Create()
{
ViewBag.ComputerBrand = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerBrand"), "KeyID", "Title");
ViewBag.ComputerOS = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerOS"), "KeyID", "Title");
ViewBag.ComputerAddedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
ViewBag.ComputerModel = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerModel"), "KeyID", "Title");
return View();
}
// POST: ComputerInventories/Create
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "RecordID,ComputerAdName,ComputerBrand,ComputerModel,ComputerSerialNumber,ComputerOS,ComputerPurchaseDate,ComputerAddedBy,ComputerArchived,ComputerArchivedDate,FileDesc,FileName,Extension,FileID")] ComputerInventory computerInventory)
{
if (ModelState.IsValid)
{
List<ComputerInventory> fileDetails = new List<ComputerInventory>();
for (int i = 0; i < Request.Files.Count; i++)
{
var file = Request.Files[i];
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
ComputerInventory fileDetail = new ComputerInventory()
{
FileName = fileName,
Extension = Path.GetExtension(fileName),
FileID = computerInventory.RecordID
};
fileDetails.Add(fileDetail);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads/"), fileDetail.FileName);
file.SaveAs(path);
}
}
computerInventory.FileID = computerInventory.FileID;
computerInventory.Extension = computerInventory.Extension;
computerInventory.FileDesc = computerInventory.FileDesc;
computerInventory.FileName = computerInventory.FileName;
db.ComputerInventories.Add(computerInventory);
db.SaveChanges();
return RedirectToAction("Index");
}
if (ModelState.IsValid)
{
try
{
db.ComputerInventories.Add(computerInventory);
db.SaveChanges();
return RedirectToAction("Index");
}
catch (Exception ex)
{
return View("Error", new HandleErrorInfo(ex, "ComputerInventories", "Create"));
}
}
ViewBag.ComputerBrand = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerBrand"), "KeyID", "Title");
ViewBag.ComputerOS = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerOS"), "KeyID", "Title");
ViewBag.ComputerAddedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
ViewBag.ComputerModel = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerModel"), "KeyID", "Title");
return View(computerInventory);
}
[HttpPost]
[ValidateAntiForgeryToken]
// GET: ComputerInventories/Edit/5
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ComputerInventory computerInventory = db.ComputerInventories.Find(id);
if (computerInventory == null)
{
return HttpNotFound();
}
ViewBag.ComputerBrand = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerBrand"), "KeyID", "Title");
ViewBag.ComputerOS = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerOS"), "KeyID", "Title");
ViewBag.ComputerAddedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
ViewBag.ComputerModel = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerModel"), "KeyID", "Title");
return View(computerInventory);
}
// POST: ComputerInventories/Edit/5
// To protect from overposting attacks, please enable the specific properties you want to bind to, for
// more details see https://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "RecordID,ComputerAdName,ComputerBrand,ComputerModel,ComputerSerialNumber,ComputerOS,ComputerPurchaseDate,ComputerAddedBy,ComputerArchived,ComputerArchivedDate,FileDesc,FileName,Extension,FileID")] ComputerInventory computerInventory)
{
if (ModelState.IsValid)
{
db.Entry(computerInventory).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ComputerBrand = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerBrand"), "KeyID", "Title");
ViewBag.ComputerOS = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerOS"), "KeyID", "Title");
ViewBag.ComputerAddedBy = new SelectList(db.ITTeamLookups, "ITTeamID", "ITTeam");
ViewBag.ComputerModel = new SelectList(db.Lookups.Where(c => c.Fieldname == "ComputerModel"), "KeyID", "Title");
return View(computerInventory);
}
// GET: ComputerInventories/Delete/5
public ActionResult Delete(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
ComputerInventory computerInventory = db.ComputerInventories.Find(id);
if (computerInventory == null)
{
return HttpNotFound();
}
return View(computerInventory);
}
// POST: ComputerInventories/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(string id)
{
ComputerInventory computerInventory = db.ComputerInventories.Find(id);
db.ComputerInventories.Remove(computerInventory);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
View
#model inventIT.Models.ComputerInventory
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Computer Assets</h2>
#using (Html.BeginForm("Create", "ComputerInventories", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Create</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.ComputerAdName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ComputerAdName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ComputerAdName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerBrand, "ComputerBrand", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ComputerBrand", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ComputerBrand, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerModel, "ComputerModel", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ComputerModel", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ComputerModel, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerSerialNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ComputerSerialNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ComputerSerialNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerOS, "ComputerOS", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ComputerOS", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ComputerOS, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerPurchaseDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ComputerPurchaseDate, new { htmlAttributes = new { #class = "form-control jqueryui-marker-datepicker" } })
#Html.ValidationMessageFor(model => model.ComputerPurchaseDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerAddedBy, "ComputerAddedBy", htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownList("ComputerAddedBy", null, htmlAttributes: new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.ComputerAddedBy, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerArchived, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.ComputerArchived)
#Html.ValidationMessageFor(model => model.ComputerArchived, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ComputerArchivedDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ComputerArchivedDate, new { htmlAttributes = new { #class = "form-control jqueryui-marker-datepicker" } })
#Html.ValidationMessageFor(model => model.ComputerArchivedDate, "", new { #class = "text-danger" })
</div>
</div>
#Html.HiddenFor(x => x.FileDesc)
<input type="file" name="file" id="file" />
<input type="submit" value="submit" />
You seems to be missing Path property in your ComputerInventory and hence in your table too. you are not setting your path to any property . How do you expect it to be saved in database?
First add a column in Table as FilePath, update Model ComputerInventory and set path to this FilePath variable
Class ComputerInventory()
{
public string FilePath { get; set; }
//other properties;
}
computerInventory.FilePath = path;
db.ComputerInventories.Add(computerInventory);
db.SaveChanges();

ASP.NET MVC - cascading drop down not being saved to database

I created a 2-dependent cascading dropdown list:
Model Classes
COUNTRIES
public int COUNTRY_ID { get; set; }
public string COUNTRY_NAME { get; set; }
STATES
public int STATE_ID { get; set; }
public Nullable<int> COUNTRY_ID { internal get; set; }
public string STATE_NAME { get; set; }
CITIES
public int CITY_ID { get; set; }
public Nullable<int> STATE_ID { internal get; set; }
public Nullable<int> COUNTRY_ID { internal get; set; }
public string CITY_NAME { get; set; }
The drop-down list worked as expected. But when clicked on save button, nothing is saved.
Controller: CITIES
// Json Call to get state
public JsonResult GetStates(string id)
{
List<SelectListItem> states = new List<SelectListItem>();
var stateList = this.Getstate(Convert.ToInt32(id));
var stateData = stateList.Select(m => new SelectListItem()
{
Text = m.STATE_NAME,
Value = m.STATE_ID.ToString(),
});
return Json(stateData, JsonRequestBehavior.AllowGet);
}
// Get State from DB by country ID
public IList<STATES> Getstate(int CountryId)
{
return _statesService.GetStates().Where(stat => stat.COUNTRY_ID == CountryId).ToList();
}
//
public ActionResult Create()
{
ViewBag.COUNTRIES = new SelectList(_countriesService.GetCountries(), "COUNTRY_ID", "COUNTRY_NAME");
ViewBag.STATES = new SelectList(_statesService.GetStates(), "STATE_ID", "state_NAME");
return View();
}
[HttpPost]
public ActionResult Create(CITIES cities)
{
try
{
IEnumerable<COUNTRIES> lstCountries = _countriesService.GetCountries();
if (ModelState.IsValid)
{
cities.ACTION_STATUS = 0;
cities.CREATED_DATE = DateTime.Now;
_citiesService.AddCity(cities);
return RedirectToAction("Index");
}
}
catch
{
ModelState.AddModelError("", "We cannot add this Cities. Verify your data entries !");
}
ViewBag.COUNTRIES = new SelectList(_countriesService.GetCountries(), "COUNTRY_ID", "COUNTRY_NAME", cities.COUNTRY_ID);
ViewBag.STATES = new SelectList(_statesService.GetStates(), "STATE_ID", "STATE_NAME", cities.STATE_ID);
return View(cities);
}
View : Cities
<div class=" box box-body box-primary">
#*#using (Html.BeginForm())*#
#using (Html.BeginForm("Create", "Cities", FormMethod.Post, new { #class = "form-horizontal", #enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, null, new { #class = "text-danger" })
<div class="row .col">
<div style="margin-top:20px" class="mainbox col-md-12 col-md-offset-0 col-sm-8 col-sm-offset-2">
<div class="panel panel-info">
<div class="panel-heading">
<div class="panel-title">Create City</div>
</div>
<div class="panel-body">
<div class="col-md-4">
<div>
#Html.LabelFor(model => model.COUNTRY_ID, "Country Name", new { #class = "control-label" })
#Html.DropDownList("COUNTRIES", ViewBag.COUNTRIES as SelectList, "-- Please Select a Country --", new { style = "width:250px" })
#Html.ValidationMessageFor(model => model.COUNTRY_ID, null, new { #class = "text-danger" })
</div>
</div>
<div class="col-md-4">
<div>
#Html.LabelFor(model => model.STATE_ID, "State Name", new { #class = "control-label" })
#Html.DropDownList("STATES", new SelectList(string.Empty, "Value", "Text"), "-- Please select a State --", new { style = "width:250px", #class = "dropdown1" })
#Html.ValidationMessageFor(model => model.STATE_ID, null, new { #class = "text-danger" })
</div>
</div>
<div class="col-md-4">
<div>
#Html.LabelFor(model => model.CITY_NAME, "City Name", new { #class = "control-label" })
#Html.TextBoxFor(model => model.CITY_NAME, new { #style = "border-radius:3px;", #type = "text", #class = "form-control", #placeholder = Html.DisplayNameFor(m => m.CITY_NAME), #autocomplete = "on" })
#Html.ValidationMessageFor(model => model.CITY_NAME, null, new { #class = "text-danger" })
</div>
</div>
</div>
<div class="panel-footer">
<div class="panel-title">
<div class="form-actions no-color">
<input type="submit" value="Create" class="btn btn-success" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
<script type="text/javascript">
$(document).ready(function () {
//Country Dropdown Selectedchange event
$("#COUNTRIES").change(function () {
$("#STATES").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetStates")', // Calling json method
dataType: 'json',
data: { id: $("#COUNTRIES").val() },
// Get Selected Country ID.
success: function (states) {
$.each(states, function (i, state) {
$("#STATES").append('<option value="' + state.Value + '">' +
state.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
When I clicked on Countries Drop-down list, it populates and the respective states are loaded as expected. When I clicked on Save button, nothing is being saved. Please what is the problem

Selected Option in dropdownlisfor not work

I have this model
public string Rol { get; set; }
[Display(Name = "Perfil:")]
[Required(ErrorMessage = "Seleccione un perfil para el usuario")]
public static IEnumerable<SelectListItem> Roles
{
get
{
yield return new SelectListItem { Text = "Administrador", Value = "1" };
yield return new SelectListItem { Text = "Consultor", Value = "2" };
}
}
public int IdProject { get; set; }
public string ProjectDesc { get; set; }
my controller:
public ActionResult _Update(string user, string name, string rol)
{
var obj = new AdministracionDto
{
User = user,
Name = name,
Rol = "2"
};
// ViewBag.Roles1 = new SelectList(AdministracionDto.Roles, "Id", "Name");
return PartialView("_Update", obj);
}
the partial view is a Pop Up, where the user click on link "Actualizar" of the view. and shows the popup
#using (Html.BeginForm("Update", "Login", FormMethod.Post, new { style = "register", style = "height: 34px;" } ))
{
<b>#Html.LabelFor(model => model.Name)</b>
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { PlaceHolder = "Ingrese nombre", #required = "required", #class = "input-register", style = "height: 34px;" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
<b>#Html.LabelFor(model => model.Rol)</b>
#Html.DropDownListFor(m => m.Rol, AdministracionDto.Roles, "--Seleccione Perfil", new { #class = "form-control", #required = "required" })
#Html.ValidationMessageFor(model => model.Rol, "", new { #class = "text-danger" })
<button type="button"class="close" data-dismiss="modal">Cancelar</button>
<button type="submit" class="signupbtn" value="Create">Actualizar</button>
}
but my problem is: that when goes to the actionresult _Update. I lose the selected value in the dropdownlisFor . but I need establish the value in "2.

Resources