POST data empty model - c#

I have View with two dropdownlists first with product category and second depends on selected category list of products. When click save button and ajax redirect to Post AddOrEditPartial in controller my model object has only autogenerated Id and CreateAt. All other data from dropdowns and quantity field are null.I cant find where is the problem. Can somebody help?
public class Warehouse : BaseEntity
{
[Required(ErrorMessage = "Category Required")]
public string IdCategory { get; set; }
[Required(ErrorMessage = "Product Required")]
public string IdProduct { get; set; }
[Required(ErrorMessage = "Quantity required")]
public int Quantity { get; set; }
}
public class WarehouseViewModel
{
public Warehouse Warehouse { get; set; }
public IEnumerable<ProductCategory> ProductCategories1 { get; set; }
public IEnumerable<Product> Products { get; set; }
}
IndexView
#using (Ajax.BeginForm("AddOrEditPartial", "Warehouse", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "formsubmit", OnSuccess = "closePopUp(data)" }))
{
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Product</h4>
</div>
<div class="modal-body" id="modbody">
#Html.Partial("AddOrEditPartial")
</div>
</div>
</div>
</div>
}
PartialView
#model MyShop.Core.ViewModels.WarehouseViewModel
<div class="panel-group">
<div class="panel-default">
<div class="panel panel-success">
<div class="panel-heading">Succes Implement Add/Edit Button</div>
<div class="panel-body" id="panbody">
<div class="col-sm-12">
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.Warehouse.Id)
<div class="form-group">
#Html.LabelFor(model => model.Warehouse.IdCategory, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Warehouse.IdCategory, new SelectList(Model.ProductCategories1, "Category", "Category"), "Please select Category", new { #class = "form-control" })
#*#Html.DropDownListFor(model => model.Warehouse.Category, (IEnumerable<SelectListItem>)new SelectList(ViewBag.Cat, "Category", "Category"), "Please select Category", new { #class = "form-control" })*#
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Warehouse.IdProduct, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.Warehouse.IdProduct, (IEnumerable<SelectListItem>)new SelectList(ViewBag.Prod, "Name", "Name"), "Please Select Product", new { #class = "form-control" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Warehouse.Quantity, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Warehouse.Quantity, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Warehouse.Quantity, "", 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-success" id="btnSubmit" />
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#Warehouse_IdCategory").change(function () {
var prodId = $(this).val();
console.log(prodId);
//debugger
$.ajax({
type: "GET",
url: '#Url.Action("GetProductList", "Warehouse")/' +prodId,
data: { prodId: prodId },
contentType: "html",
success: function (response) {
//debugger
$("#Warehouse_IdProduct").empty();
$("#Warehouse_IdProduct").append(response);
}
})
})
})
</script>
Controller
public ActionResult Index()
{
WarehouseViewModel whViewModel = new WarehouseViewModel();
whViewModel.Warehouse = new Warehouse();
whViewModel.ProductCategories1 = productCategories.Collection();
whViewModel.Products = contextProduct.Collection();
return View(whViewModel);
}
[HttpPost]
public ActionResult AddOrEditPartial(Warehouse wh)
{
if (!ModelState.IsValid)
{
return Json(new { success = false });
}
else
{
var data = context.Find(wh.Id);
if (data != null)
{
data.IdProduct = wh.IdProduct;
data.IdCategory = wh.IdCategory;
data.Quantity = wh.Quantity;
context.Commit();
}
else
{
context.Insert(wh);
context.Commit();
}
return Json(new { success = true });
}
}

Change type of your IdCategory & IdProduct to int and it should work.
public class Warehouse : BaseEntity
{
[Required(ErrorMessage = "Category Required")]
public int IdCategory { get; set; }
[Required(ErrorMessage = "Product Required")]
public int IdProduct { get; set; }
[Required(ErrorMessage = "Quantity required")]
public int Quantity { get; set; }
}

#UmairZafar
public class ProductCategory : BaseEntity
{
[Required(ErrorMessage="Please fill category")]
public string Category { get; set; }
}
public class Product : BaseEntity
{
[StringLength(20)]
[DisplayName("Product Name")]
[Required(ErrorMessage = "Please fill product name")]
public string Name { get; set; }
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Range(0,1000)]
public decimal Price { get; set; }
public string Category { get; set; }
public string Image { get; set; }
}
public abstract class BaseEntity
{
public string Id { get; set; }
public DateTimeOffset CreatedAt { get; set; }
public BaseEntity()
{
Id = Guid.NewGuid().ToString();
CreatedAt = DateTime.Now;
}
}

Related

C# MVC Ajax Form Modal DropDownList Validation Error

I am using a Dropdownlist in my modal I have it working perfectly with textboxes. I’ve tried changing my Model to multiple different properties (String, Int, SelectListItem). I feel I must be extremely close to getting this to work. I would like my validation message to appear when im using Dropdownlists as well. When the validation message is suppose to appear I get the error message ‘The ViewData item that has the key 'PartVM.IDenteredBy' is of type 'System.Int32' but must be of type 'IEnumerable'.’ Here is my View, Model, and Action.
public class UpdatePartViewModel
{
public int PartID { get; set; }
[Required]
[Display(Name = "Part Number")]
public string PartNumber { get; set; }
//[Required]
[Display(Name = "Entered By")]
public string EnteredBy { get; set; }
public SelectListItem SLIenteredBy { get; set; }
public IEnumerable<SelectListItem> EnteredByOptions { get; set; }
public int IDenteredBy { get; set; }
[Display(Name = "Date Entered")]
public DateTime DateEntered { get; set; }
[Display(Name = "Machine Types")]
public List<int> MachineTypes { get; set; }
//public string MachineTypesString { get; set; }
}
public class FindPartModel
{
[Display(Name = "Entered By")]
public string PNEnteredBy { get; set; }
public IEnumerable<SelectListItem> PNEnteredByOptions { get; set; }
public findPartNumberListAttributes[] info { get; set; }
public List<findPartNumberListAttributes> reportList { get; set; }
public UpdatePartViewModel PartVM { get; set; }
}
//PNControls.cshtml VIEW
#model Messer_PartNumbers.Models.FindPartModel
#{ HtmlHelper.UnobtrusiveJavaScriptEnabled = true; }
#Html.AntiForgeryToken()
#Html.HiddenFor(x => x.PartVM.PartID)
#Html.HiddenFor(x => x.PartVM.PartGroup)
<div class="form-group">
#Html.LabelFor(x =>x.PartVM.PartNumber, htmlAttributes: new { #class="control-label col-3" })
<div class="col-9">
#Html.TextBoxFor(x => x.PartVM.PartNumber, new { #class="form-control", #readonly="readonly" })
#Html.ValidationMessageFor(x => x.PartVM.PartNumber, "", new { #class="text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(x => x.PartVM.EnteredBy, htmlAttributes: new { #class = "control-label col-3" })
<div class="col-9">
#*#Html.TextBoxFor(x => x.PartVM.EnteredBy, new { #class="form-control" })*#
#*#Html.DropDownListFor(x => x.PartVM.SLIenteredBy, Model.PNEnteredByOptions as IEnumerable<SelectListItem>, "Select User", new { #class = "form-control" })*#
#*#Html.DropDownList("DDLenteredBy", Model.PNEnteredByOptions as IEnumerable<SelectListItem>, new { #class="form-control" })*#
#Html.DropDownListFor(x => x.PartVM.IDenteredBy, Model.PNEnteredByOptions as IEnumerable<SelectListItem>, "Select User", new { #class = "form-control" })
#*#Html.ValidationMessageFor(x => x.PartVM.EnteredBy, "", new { #class = "text-danger" })*#
#*#Html.ValidationMessageFor(x => x.PartVM.SLIenteredBy, "", new { #class = "text-danger" })*#
#Html.ValidationMessageFor(x => x.PartVM.IDenteredBy, "", new { #class = "text-danger" })
</div>
</div>
#using (Ajax.BeginForm("PartNumberUpdate", "Parts", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "PartNumControls", OnSuccess = "ajaxPartUpdate" }))
{
<div class="modal" id="modalPNUpdate" tabindex="-1" role="dialog" aria-labelledby="lblPNUpdate" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title">Part Number Details</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="PartNumControls">
#Html.Partial("PNControls")
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" value="Save" />
</div>
</div>
</div>
</div>
}
[HttpPost]
[ValidateAntiForgeryToken]
[HandleError]
public ActionResult PartNumberUpdate(FindPartModel model)
{
if (ModelState.IsValid)
{
var partNumber = context.PartNumbers.Where(x => x.PartNumber1 == model.PartVM.PartNumber).FirstOrDefault();
// Updating the Parts data with the new Models Information.
partNumber.PartNumber1 = model.PartVM.PartNumber;
partNumber.PartGroup = model.PartVM.PartGroup != null ? model.PartVM.PartGroup : partNumber.PartGroup;
partNumber.Last4Number = model.PartVM.Last4Numbers;
//var str = Request.Form["DDLenteredBy"];
//if(model.PartVM.EnteredBy != null)
//{ var enteredByID = context.Employees.Where(e => e.Name == model.PartVM.EnteredBy).Select(x => x.ID).FirstOrDefault();
// partNumber.EnteredBy = enteredByID; }
/* testvar2 = testVar1 != null ? testvar1 : testvar2; || testVar2 = testVar1 ?? testVar2 */
partNumber.EnteredBy = model.PartVM.IDenteredBy;
partNumber.DateEntered = model.PartVM.DateEntered;
/// UPDATE PartNumber Record
context.Entry(partNumber).State = EntityState.Modified;
context.SaveChanges();
ViewBag.ValidMessage = "PartNumber Record Updated";
string returnStr = "refresh";
ModelState.Clear();
return Json(returnStr);
}
TempData["ErrorState"] = "x";
return PartialView("PNControls", model);
}
public ActionResult PNControls()
{
return View(new FindPartModel());
}
I needed to repopulate my Dropdownlists when the ModelState was invalid.
Now my validation with ajax works exactly as expected. I needed this at the end of my PartNumberUpdate Action.
}
/// Populate DropDownLists in Modal to UPDATE fields
var fetcher = new DataFetcher();
model.PNEnteredByOptions = fetcher.EnteredByInfo();
//ViewBag.DDLenteredby = fetcher.EnteredByInfo();
model.PNMachineTypeOptions = fetcher.machineTypeInfo();
model.PNSoftwareTypeOptions = fetcher.softwareTypeInfo();
model.PNManufacturerOptions = fetcher.manufactuerInfo();
model.PNUsageOptions = fetcher.usageInfo();
model.PNUnitsOptions = fetcher.unitsInfo();
TempData["ErrorState"] = "x";
return PartialView("PNControls", model);
}

ASP.NET MVC Viewmodel Edit returns empty fields (item is not identified by id)

I previously reveived some help here but some problems with the "Edit" arouse now. Currently stuck at HttpGet, HttpPost is yet to come.
In short, whenever I click on an existing item to edit, instead of the expected values, it returns an empty form, as seen here. (You might think that the reason for this is because I use the same exact view for Create and Edit but unfortunately this isn't, even when I used to separate ones, had the same result.)
Town.cs
using System.Collections.Generic;
namespace City.Models
{
public class Town
{
public Town()
{
Streets = new List<Street>();
}
public int TownId { get; set; }
public string TownName { get; set; }
public virtual ICollection<Street> Streets { get; set; }
}
}
Street.cs
using System.Collections.Generic;
namespace City.Models
{
public class Street
{
public Street()
{
Houses = new List<House>();
}
public int StreetId { get; set; }
public string StreetName { get; set; }
public virtual ICollection<House> Houses { get; set; }
}
}
House.cs
using System.Collections.Generic;
namespace City.Models
{
public class House
{
public House()
{
Floors = new List<Floor>();
}
public int HouseId { get; set; }
public string HouseName { get; set; }
public ICollection<Floor> Floors { get; set; }
}
}
Floor.cs
using System.Collections.Generic;
namespace City.Models
{
public class Floor
{
public Floor()
{
FireExtinguishers = new List<FireExtinguisher>();
}
public int FloorId { get; set; }
public int FloorNumber { get; set; }
public virtual ICollection<FireExtinguisher> FireExtinguishers { get; set; }
}
}
FireExtinguisher.cs
using System.ComponentModel;
namespace City.Models
{
public class FireExtinguisher
{
public int FireExtinguisherId { get; set; }
[DisplayName("Fire Extinguisher")]
public string FireExtinguisherName { get; set; }
public int FloorId { get; set; }
public int HouseId { get; set; }
public int StreetId { get; set; }
public int TownId { get; set; }
public Floor Floor { get; set; }
public House House { get; set; }
public Street Street { get; set; }
public Town Town { get; set; }
}
}
MyViewModel.cs
using System.Collections.Generic;
namespace City.Models
{
public class MyViewModel
{
public IEnumerable<Town> TownId { get; set; }
public IEnumerable<Street> StreetId { get; set; }
public IEnumerable<House> HouseId { get; set; }
public IEnumerable<Floor> FloorId { get; set; }
public FireExtinguisher FireExtinguisher { get; set; }
public string FireExtinguisherName { get; set; }
}
}
Create/Edit view
#model City.Models.MyViewModel
<h2>Add new or edit existing FE</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="col-md-12">
<div class="form-group">
#Html.LabelFor(model => model.TownId, "Town", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.TownId, new SelectList(Model.TownId, "TownId", "TownName"), "Choose Town", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TownId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StreetId, "Street", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StreetId, new SelectList(Model.StreetId, "StreetId", "StreetName"), "Choose Street", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StreetId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HouseId, "House", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.HouseId, new SelectList(Model.HouseId, "HouseId", "HouseName"), "Choose House", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.HouseId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FloorId, "Floor", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.FloorId, new SelectList(Model.FloorId, "FloorId", "FloorNumber"), "Choose Floor", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.FloorId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FireExtinguisherName, "Fire Extinguisher", new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.TextBoxFor(model => model.FireExtinguisherName, new { #class = "form-control", Value = "" })
#Html.ValidationMessageFor(model => model.FireExtinguisherName, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div>
<div>
<input type="submit" value="Do it" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Homecontroller.cs
using System;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using City.Models;
namespace City.Controllers
{
public class HomeController : Controller
{
private ApplicationDbContext db;
private MyViewModel viewModel;
public HomeController()
{
db = new ApplicationDbContext();
var town = db.Towns.ToList();
var street = db.Streets.ToList();
var house = db.Houses.ToList();
var floor = db.Floors.ToList();
viewModel = new MyViewModel()
{
TownId = town,
StreetId = street,
HouseId = house,
FloorId = floor
};
}
public ActionResult Index()
{
return View(db.FireExtinguishers.ToList());
}
[HttpGet]
public ActionResult Create()
{
return View(viewModel);
}
[HttpPost]
public ActionResult Create(FireExtinguisher fe)
{
if (ModelState.IsValid)
{
db.FireExtinguishers.Add(fe);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(viewModel);
}
[HttpGet]
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var fe = db.FireExtinguishers.Find(id);
var town = db.Towns.ToList();
var street = db.Streets.ToList();
var house = db.Houses.ToList();
var floor = db.Floors.ToList();
viewModel = new MyViewModel()
{
FireExtinguisher = fe,
TownId = town,
StreetId = street,
HouseId = house,
FloorId = floor
};
return View("Create", viewModel);
}
[HttpPost]
public ActionResult Edit()
{
throw new NotImplementedException();
}
}
}
Any help would be appreciated, thank you
Personally I like to use View- and Post-Models for that as a clear statement, what is send to the View (ViewModel) and what is send back via Post. As a naming convention the name of the model class Takes the controller name and the action name.
I start with the PostModel, which would be in your case
public class HomeEditPostModel
{
[Required]
[MaxLength(50)]
public string Name { get; set; }
[Required]
public int TownId { get; set; }
[Required]
public int StreetId { get; set; }
[Required]
public int HouseId { get; set; }
[Required]
public int FloorId { get; set; }
}
Now for the view we need some collections for the dropdown fields, where we can select from
public class SelectionItem<TKey>
{
public TKey Key { get; set; }
public string DisplayName { get; set; }
}
public class HomeEditViewModel : HomeEditPostModel
{
public IEnumerable<SelectionItem<int>> Town { get; set; }
public IEnumerable<SelectionItem<int>> Street { get; set; }
public IEnumerable<SelectionItem<int>> House { get; set; }
public IEnumerable<SelectionItem<int>> Floor { get; set; }
}
Now the view
#model WebApplication6.Models.HomeEditViewModel
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>HomeEditSubmitModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TownId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.TownId, new SelectList(Model.Town, "Key", "DisplayName"), "Choose Town", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.TownId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.StreetId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.StreetId, new SelectList(Model.Street, "Key", "DisplayName"), "Choose Street", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.StreetId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HouseId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.HouseId, new SelectList(Model.House, "Key", "DisplayName"), "Choose House", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.HouseId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FloorId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.DropDownListFor(model => model.FloorId, new SelectList(Model.Floor, "Key", "DisplayName"), "Choose Floor", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.FloorId, "", 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")
}
and finally the controller (only relevant parts)
public class HomeController : Controller
{
[HttpGet]
public ActionResult Edit(int id)
{
// just some fake data for demonstration
var model = new HomeEditViewModel
{
Name = "Name",
Floor = Enumerable.Range(1, 10).Select(e => new SelectionItem<int> { Key = e, DisplayName = $"Floor {e}" }),
Street = Enumerable.Range(1, 10).Select(e => new SelectionItem<int> { Key = e, DisplayName = $"Street {e}" }),
House = Enumerable.Range(1, 10).Select(e => new SelectionItem<int> { Key = e, DisplayName = $"House {e}" }),
Town = Enumerable.Range(1, 10).Select(e => new SelectionItem<int> { Key = e, DisplayName = $"Town {e}" }),
FloorId = 3,
StreetId = 4,
HouseId = 5,
TownId = 6,
};
return View(model);
}
[HttpPost]
public ActionResult Edit(int id, HomeEditPostModel model)
{
// needs to save the data here
return RedirectToAction(nameof(Index));
}
}

Can not insert my dropdownlist data in database with foreign key in mvc4

I want to pack my data in form with foreign key and send that to database.I collect data from database with controller and show in my view and when I complete the form can not send that to database and see the exception
my controller code is
public ActionResult Register()
{
testContext test = new testContext();
List<SelectListItem> listselecteditem = new List<SelectListItem>();
foreach (Gender item in test.genders)
{
SelectListItem selectlist = new SelectListItem()
{
Text = item.GenderType,
Value = item.GenderID.ToString(),
};
listselecteditem.Add(selectlist);
}
ViewBag.Datalist = new SelectList(listselecteditem, "Value", "Text");
return View();
}
this controller get data from database and send to dropdownlist
and this controller save my data in database
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(Person p)
{
using (testContext test=new testContext())
{
if (ModelState.IsValid)
{
try
{
test.persons.Add(p);
test.SaveChanges();
ViewBag.Message="Success";
}
catch (Exception ec)
{
ViewBag.Message = ec.Message;
}
}
}
return View(p);
}
this is my view
#model testmvc.Models.Person
<div class="container">
<div class="row">
<div class="pull-right col-sm-offset-3 col-sm-6">
<div class="panel panel-default">
<div class="panel-heading ">
<p>register</p>
</div>
<div class="panel-body">
#using (Html.BeginForm("Register", "RegisterLogin", FormMethod.Post, new { #class = "form-horizontal" }))
{
#Html.ValidationSummary(true)
<fieldset>
#Html.AntiForgeryToken()
#if (ViewBag.Messsage != null)
{
<div class="alert alert-success">
<p>#ViewBag.Message</p>
</div>
}
<div class="form-group">
#Html.TextBoxFor(model => model.Fullname, new { #class = "form-control", #placeholder = "Full name" })
</div>
<div class="form-group">
#Html.TextBoxFor(model => model.Username, new { #class = "form-control input-sm", #id = "last_name", #placeholder = "Username" })
</div>
<div class="form-group">
#Html.TextBoxFor(model => model.EmailAddress, new { #class = "form-control input-sm", #id = "email", #placeholder = "Email address" })
</div>
<div class="form-group">
#Html.TextBoxFor(model => model.Password, new { #class = "form-control input-sm floatlabel", #id = "first_name", #placeholder = "Password" })
</div>
<div class="form-group">
#Html.TextBoxFor(model => model.Comfirmpassword, new { #class = "form-control input-sm", #id = "last_name", #placeholder = "confirmpassword" })
</div>
<div class="form-group">
#*<select>
#foreach (var item in ViewBag.DataList)
{
<option>#item.Text</option>
}
</select>*#
#Html.DropDownList("Datalist",String.Empty)
</div>
<div class="form-group">
#Html.TextBoxFor(model => model.Birthday, new { #class = "form-control input-sm", #id = "password_confirmation", #placeholder = "Birthday yyyy/dd/mm" })
</div>
<div>
<input type="submit" value="Register" class="btn btn-primary">
</div>
</fieldset>
}
</div>
</div>
</div>
</div>
</div>
and my model code
public partial class Person
{
[Key]
public int personID { get; set; }
[Required]
public String Fullname { get; set; }
[Required]
public String Username { get; set; }
[Required]
public String Password { get; set; }
[Required]
[NotMapped]
public String Comfirmpassword { get; set; }
[Required]
public String EmailAddress { get; set; }
[DataType(DataType.DateTime)]
[Required]
public DateTime Birthday { get; set; }
public int GenderID { get; set; }
[ForeignKey("GenderID")]
public virtual Gender Gender { get; set; }
}
[Table("Gender")]
public partial class Gender
{
[Key]
public int GenderID { get; set; }
[Required]
public String GenderType { get; set; }
public virtual ICollection<Person> Persons { get; set; }
}
this exception said there is not any viewdata key with "Datalist". how can I solve that and what is my code problem
The reason you are getting this exception is because inside [HttpPost] action you didn't populate the ViewBag.Datalist property, the way you did in your Get action. Since you redisplay the same view and this view requires this information in order to properly render the dropdown, you will need to populate it. To avoid repetition you could place this logic in a separate method:
private SelectList GetGenders()
{
using (testContext test = new testContext())
{
List<SelectListItem> listselecteditem = new List<SelectListItem>();
foreach (Gender item in test.genders)
{
SelectListItem selectlist = new SelectListItem()
{
Text = item.GenderType,
Value = item.GenderID.ToString(),
};
listselecteditem.Add(selectlist);
}
return new SelectList(listselecteditem, "Value", "Text");
}
}
which you are going to call in your 2 actions:
public ActionResult Register()
{
ViewBag.Datalist = GetGenders();
return View();
}
and:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Register(Person p)
{
using (testContext test = new testContext())
{
if (ModelState.IsValid)
{
try
{
test.persons.Add(p);
test.SaveChanges();
ViewBag.Message = "Success";
}
catch (Exception ec)
{
ViewBag.Message = ec.Message;
}
}
}
ViewBag.Datalist = GetGenders();
return View(p);
}

How to save data from Select box in Entity Framework Database relation Many to Many

How to save data from Select box in Entity Framework Database relation Many to Many
There are two classes one weapon and other User..
public class Weapon { } public class User { }
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
}
public class Wepon
{ public int ID { get; set; }
public string Wepon_Name { get; set; }
public int Power { get; set; }
}
Which should have relation Many to Many Using FormCollection and Model
User Class
And Weapon Class
public class User
{
public int ID { get; set; }
public string Name { get; set; }
public string Type { get; set; }
**public List<Wepon> WeposInList { get; set; }**
}
public class Wepon
{
public int ID { get; set; }
public string Wepon_Name { get; set; }
public int Power { get; set; }
public List<User> UsersHaveWeponsList { get; set; }// User the List for M to M
}
DBContext
public class DbContexFor : DbContext
{
public DbContexFor()
: base("name=ConnectionStringName")
{
}
public virtual DbSet<User> Users { get; set; }
public virtual DbSet<Wepon> Wepons { get; set; }
}
}
**
The Controller Code
**
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "ID,Name,Type")] User user, FormCollection formData)
{
if (ModelState.IsValid)
{
var ss = formData["ShipFromCountries"].ToString();
user.WeposInList = db.Wepons.Where(c => c.Wepon_Name == ss).ToList();
db.Users.Add(user);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(user);
}
And the Html Code
#model enumVarAction.Models.User
#{
var list = ViewBag.MyList;
ViewBag.Title = "Create";
}
Create Html Page
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>User</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Type, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Type, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Type, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.WeposInList, htmlAttributes: new { #class = "control-label col-md-2" })
<select id="ShipFromCountries" multiple="multiple" name="ShipFromCountries">
<div class="col-md-10">
#foreach (var VARIABLE in list)
{
<option value="#VARIABLE.Wepon_Name">#VARIABLE.Wepon_Name</option>
}
</div>
</select>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
**
Debug at Controller
**
**
Data is Database
**

Upload image to SQL server using view, view model, and controller

I'm in VS 2013 and am completely new to ASP.NET MVC in general. I have been attempting to do this for sometime with no luck. Have a user complete a form with an image upload, and have that form with the image written to the DB. I know its best to write the path to the DB and store the image in the content folder of the application but I have no idea how to do any of this. Can someone give me a starting point?
I also have a ClientUtility.cs that is used to populate drop-downs but I don't see this being needed right now.
Currently the data type for the image ref in the db is VARCHAR(255).
Controller:
private TpsEntities db = new TpsEntities();
[HttpPost]
public ActionResult SaveStaffDetails(RegisterStaffViewModel model)
{
var staff = new staffTable()
{
staffFirstName = model.FirstName,
staffLastName = model.LastName,
staffTitle = model.SelectedTitle,
staffAddress = model.Address,
staffCity = model.City,
staffState = model.SelectedState,
staffZip = model.ZipCode,
staffExperience = model.SelectedExperience,
staffEducation = model.SelectedEducation,
desiredSalary = model.SelectedSalary,
staffProfession = model.SelectedProfession,
staffAvailibity = model.SelectedAvailability,
staffEmail = model.EmailAddress,
staffPhoneNum = model.PhoneNumber,
staffPhoto = null,
userID = model.UserId
};
using (var db = new TpsEntities())
{
db.staffTables.Add(staff);
db.SaveChanges();
}
var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = userManager.FindById(model.UserId);
userManager.AddToRole(model.UserId, "Staff");
ClaimsIdentity identity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
identity.AddClaim(new Claim(ClaimTypes.Role, "Staff"));
var AuthenticationManager = System.Web.HttpContext.Current.GetOwinContext().Authentication;
AuthenticationManager.SignIn(new AuthenticationProperties() {IsPersistent = false}, identity);
return RedirectToAction("Index", "Home");
}
}
ViewModel:
public class RegisterStaffViewModel
{
[Required]
[Display(Name = "First Name")]
public string FirstName { get; set; }
[Required]
[Display(Name = "Last Name")]
public string LastName { get; set; }
[Required]
[Display(Name = "Address")]
public string Address { get; set; }
public System.Web.UI.WebControls.ListItemCollection Title { get; set; }
[Required]
[Display(Name = "Title")]
public string SelectedTitle { get; set; }
[Required]
[Display(Name = "City")]
public string City { get; set; }
public System.Web.UI.WebControls.ListItemCollection States { get; set; }
[Required]
[Display(Name = "State")]
public string SelectedState { get; set; }
[Required]
[Display(Name = "Zip Code")]
public double? ZipCode { get; set; }
[Required]
[Phone]
[Display(Name = "Phone Number")]
public string PhoneNumber { get; set; }
[Required]
[EmailAddress]
[Display(Name = "Email Address")]
public string EmailAddress { get; set; }
public System.Web.UI.WebControls.ListItemCollection Experience { get; set; }
[Required]
[Display(Name = "Experience")]
public string SelectedExperience { get; set; }
public System.Web.UI.WebControls.ListItemCollection Education { get; set; }
[Required]
[Display(Name = "Education")]
public string SelectedEducation { get; set; }
public System.Web.UI.WebControls.ListItemCollection Salary { get; set; }
[Required]
[Display(Name = "Salary")]
public string SelectedSalary { get; set; }
public System.Web.UI.WebControls.ListItemCollection Profession { get; set; }
[Required]
[Display(Name = "Profession")]
public string SelectedProfession { get; set; }
public System.Web.UI.WebControls.ListItemCollection Availability { get; set; }
[Required]
[Display(Name = "Availability")]
public string SelectedAvailability { get; set; }
public string UserId { get; set; }
}
View:
#*Start of Registration Form for Staff*#
#using (Html.BeginForm("SaveStaffDetails", "Staff", FormMethod.Post, new { #class = "form-horizontal", role = "form" }))
{
#Html.AntiForgeryToken()
#Html.HiddenFor(m => m.UserId)
<fieldset>
<!-- Form Name -->
<legend>Register New Staff</legend>
#*First Name*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.FirstName, new { #class = "form-control input-md", #placeholder = "First Name" })
</div>
</div>
#*Last Name*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.LastName, new { #class = "form-control input-md", #placeholder = "Last Name" })
</div>
</div>
#*Person Title*#
<div class="form-group">
<label class="col-md-6 control-label" for="title">Title</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedTitle, new SelectList(Model.Title, "Text", "Value"))
</div>
</div>
#*Address Line*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.Address, new { #class = "form-control input-md", #placeholder = "Address" })
</div>
</div>
#*City*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.City, new { #class = "form-control input-md", #placeholder = "City" })
</div>
</div>
#*State*#
<div class="form-group">
<label class="col-md-6 control-label" for="state">State</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedState, new SelectList(Model.States, "Text", "Value"))
</div>
</div>
#*Zip Code*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.ZipCode, new { #class = "form-control input-md", #placeholder = "Zip Code" })
</div>
</div>
#*Phone Number*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.PhoneNumber, new { #class = "form-control input-md", #placeholder = "Phone Number" })
</div>
</div>
#*Email Address*#
<div class="form-group">
<div class="col-md-6">
#Html.TextBoxFor(m => m.EmailAddress, new { #class = "form-control input-md", #placeholder = "Email Address" })
</div>
</div>
#*Experience*#
<div class="form-group">
<label class="col-md-6 control-label" for="experience">Experience</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedExperience, new SelectList(Model.Experience, "Text", "Value"))
</div>
</div>
#*Education*#
<div class="form-group">
<label class="col-md-6 control-label" for="education">Education</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedEducation, new SelectList(Model.Education, "Text", "Value"))
</div>
</div>
#*Desired Salary*#
<div class="form-group">
<label class="col-md-6 control-label" for="salary">Desired Salary</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedSalary, new SelectList(Model.Salary, "Text", "Value"))
</div>
</div>
#*Profession*#
<div class="form-group">
<label class="col-md-6 control-label" for="profession">Profession</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedProfession, new SelectList(Model.Profession, "Text", "Value"))
</div>
</div>
#*Availability*#
<div class="form-group">
<label class="col-md-6 control-label" for="availability">Availability</label>
<div class="col-md-6">
#Html.DropDownListFor(m => m.SelectedAvailability, new SelectList(Model.Availability, "Text", "Value"))
</div>
</div>
<!-- INSERT IMAGE UPLOAD HERE -->
</fieldset>
<input type="submit" value="Save" />
}
Edit your controller as the following code.I assumed that staffPhoto is taking picturepath.
public ActionResult SaveStaffDetails(RegisterStaffViewModel model,HttpPostedFileBase image)
{
if (Request.Files.Count > 0) {
string FileName = Guid.NewGuid().ToString().Replace("-", "");
string Path = System.IO.Path.GetExtension(Request.Files[0].FileName);
string FullPath = "~/Images/StaffPhotos/" + FileName + Path;
Request.Files[0].SaveAs(Server.MapPath(FullPath));
staffPhoto = FileName + Path;
}
}
In your view you need a file post input
<input type="file" class="filestyle" name="image" data-classbutton="btn btn-primary" data-input="false">

Categories

Resources