getting null reference in create view - c#

I have created a method in the Employee controller for creating a new Employee:
[HttpGet]
[ActionName ("Create")]
public ActionResult Create()
{
return View();
}
I have Added a view for Create method with Employee(strongly-typed)model and used the create template.
When I run the program and click on create new I get a null reference error in create view.
#model BuissnessLayer.Employee
#{
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Employee</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.Employee_Id, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_Id, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_Id, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee_Name, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_Name, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_Name, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee_Age, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_Age, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_Age, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee_City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_City, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_City, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Employee_Salary, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Employee_Salary, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Employee_Salary, "", 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>
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
I get the error at line
#Html.EditorFor(model => model.Employee_Id, new { htmlAttributes = new { #class = "form-control" } })
I don't know how to solve the problem because the code is created automatically and i haven't edited anything yet.

You should pass model to your View..
[HttpGet]
[ActionName ("Create")]
public ActionResult Create()
{
var model = new Employee(){}
return View(model);
}
#model BuissnessLayer.Employee

Related

How to get back uploaded image in edit mode in my form using ASP.NET MVC 5?

I have created a form and I am inserting some data and image in my database using the form submit... But when I am opening in edit mode, all inserted data is available in the input fields except the image? How do I fix this?
View:
#model User_Management_System_V2._0.Models.Product
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm("Edit","Products",FormMethod.Post , new { enctype = "multipart/form-data"}))
{
#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.ProductID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ProductID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ProductID, "", new { #class = "text-danger" })
</div>
</div>*#
#Html.HiddenFor(model => model.ProductName)
<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.PriceExpected, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PriceExpected, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PriceExpected, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.OldTime, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.OldTime, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.OldTime, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Status, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Status, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Status, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Photo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<input type="file" name="file"/>
#Html.ValidationMessageFor(model => model.Photo, "", 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>
Controller:
public ActionResult Edit(string id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Product product = db.Products.Find(id);
if (product == null)
{
return HttpNotFound();
}
return View(product);
}
Create Action
public ActionResult Create()
{
return View();
}
[HttpPost]
public ActionResult Create([Bind(Include = "ProductName,Description,PriceExpected,OldTime,Status,Photo")]Product product,HttpPostedFileBase file)
{
if (file != null)
{
product.Photo = new byte[file.ContentLength];
file.InputStream.Read(product.Photo, 0, file.ContentLength);
}
else
{
ModelState.AddModelError("", "Please Select image");
}
db.Products.Add(product);
db.SaveChanges();
return RedirectToAction("Index");
}
My main problem is that all the fields are opening in edit mode which means they are opening in edit mode with the preinserted data values in their fields but the image is not having the preinserted value.
try the following solution in jquery and pure Javascript you will only need to retrieve byte array of the image you uploaded and it's extension then just give your image control the generated src I hope it helps
var PhotoArr = []; //array of bytes from the server
var PhotoExt = "jpg";//example
if (PhotoArr) {
var byteArray = new Uint8Array(oldResume.PhotoArr);
var blob = new Blob([byteArray], { type: 'application/' + PhotoExt });
var image = $('#yourImageId');
var urlCreator = window.URL || window.webkitURL;
var imageUrl = urlCreator.createObjectURL(blob);
image.attr('src', imageUrl);
}

getting my form to autofill when editing using

very new to mvc. My problem is when I have a record I want to edit my view does not autofill the form. Specifically I am trying to enter a bid on an auction site. I want everything else to stay the same and only update the bid. if my form doesn't autofill then everything would be null. any help would be appreciated.
this is from the CarAuctionController
// GET: CarAuction/Edit/5
public ActionResult Edit(int id= 3)
{
CarList carList = db.CarLists.Find(id);
return View();
}
// POST: CarAuction/Edit/5
[HttpPost]
public ActionResult Edit(CarList carlist)
{
try
{
// TODO: Add update logic here
if (ModelState.IsValid)
{
db.Entry(carlist).State=EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View("Index");
}
catch
{
return View();
}
}
this is from the view Edit.cshtml
#model ClassicCarAuction.CarList
#{
ViewBag.Title = "Edit";
}
<h2>Edit</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>CarList</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.ID)
<div class="form-group">
#Html.LabelFor(model => model.ModelYear, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ModelYear, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ModelYear, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Make, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Make, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Make, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Model, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Model, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Model, "", 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.CarImage, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CarImage, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CarImage, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.DatePosted, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.DatePosted, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.DatePosted, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.AuctionEndDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.AuctionEndDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.AuctionEndDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ReserveBid, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ReserveBid, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ReserveBid, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.PosterUserID, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.PosterUserID, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.PosterUserID, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ViewingLocation, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ViewingLocation, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ViewingLocation, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HighestBid, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HighestBid, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HighestBid, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.HighBidUserId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.HighBidUserId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.HighBidUserId, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Status, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Status, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Status, "", 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")
}
The problem is that you returning "view", but you do not supply the "model" in which the engine can bind them together, thus the default is null.
return View("Index");
should be
return View("Index", carlist);
You are not passing the retrieved carlist model to the view. Therefore the view does not have access to the model and is not able to fill in the form.
// GET: CarAuction/Edit/5
public ActionResult Edit(int id= 3)
{
CarList carList = db.CarLists.Find(id);
// Change this:
return View(carList);
}

How to pass a value of class from view to controller in ASP.Net MVC

I can retrieve a string in this but when I try retrieving a class I'm having an exception error.
Customer = new Customer()
{
FirstName = Request.Form["FirstName"],
LastName = Request.Form["LastName "],
BillingAddress = new Address
{
StreetAddress1 = Request.Form["StreetAddress1"],
}
I already tried setting a value, it saves successfully, but when I'm getting the data from the value exception error occurs.By the way I'm using a model from the SDK. Thank you
View form
#model WebApplication16.Model.ParentModel
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>ParentModel</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<div class="form-group">
#Html.LabelFor(model => model.Customer.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Customer.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Customer.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Customer.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Customer.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Customer.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Customer.BillingAddress.StreetAddress1, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Customer.BillingAddress.StreetAddress1, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Customer.BillingAddress.StreetAddress1, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Customer.BillingAddress.StreetAddress2, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Customer.BillingAddress.StreetAddress2, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Customer.BillingAddress.StreetAddress2, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Customer.BillingAddress.City, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Customer.BillingAddress.City, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Customer.BillingAddress.City, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Customer.BillingAddress.StateCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Customer.BillingAddress.StateCode, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Customer.BillingAddress.StateCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Customer.BillingAddress.Country, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Customer.BillingAddress.Country, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Customer.BillingAddress.Country, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Customer.BillingAddress.ZipCode, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Customer.BillingAddress.ZipCode, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Customer.BillingAddress.ZipCode, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreditCard.CreditCardNumber, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CreditCard.CreditCardNumber, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CreditCard.CreditCardNumber, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreditCard.ExpirationDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CreditCard.ExpirationDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CreditCard.ExpirationDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.CreditCard.Issuer, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.CreditCard.Issuer, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.CreditCard.Issuer, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Payment.Amount, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Payment.Amount, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Payment.Amount, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Payment.Cvv, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Payment.Cvv, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Payment.Cvv, "", new { #class = "text-danger" })
</div>
</div>
<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>
Simple answer: You can't send complex datatypes in a form.
For your given example, you can just send "StreetAddress1" as a string (alongside with "FirstName" and "LastName") and build the Customer object in your controller.
Code for your view:
#model Customer
<div>
#using (Html.BeginForm("Action", "Controller", FormMethod.Post))
{
#Html.TextBoxFor(m => m.FirstName)<br />
#Html.TextBoxFor(m => m.LastName)<br />
#Html.TextBoxFor(m => m.BillingAddress)<br />
<button type="submit">Save</button>
}
</div>
If you follow this approach, MVC already serializes the Customer object for you:
[HttpPost]
public ActionResult Action(Customer c)
{
string FullName = c.FirstName + " " + c.LastName
}
Use FormCollection Class in You Controller .. This Will Get You All The Posted Values From Use .. Then u Can Extract Values By Key FromCollection Keys .. Create New Object Based On The Value You Got From The FormCollection , Simply Add a FromCollection Parameter
public ActionResult (FormCollection F)
{
}

Asp.net mvc DropdownList giving null reference error

I am trying to populate a dropdownlist and then post it to db but for some reason it is giving error, please advice.
Controller
public class StudentController : BaseController
{
private List<SelectListItem> _gendersList;
[HttpGet]
public ActionResult Create()
{
var model = new CreateStudent();
_gendersList = new List<SelectListItem>()
{
new SelectListItem { Text = Constants.Gender.Boy, Value = Constants.Gender.Boy},
new SelectListItem { Text = Constants.Gender.Girl, Value = Constants.Gender.Girl},
};
model.Genders = _gendersList;
return View(model);
}
[HttpPost]
public ActionResult Create(CreateStudent student)
{
var result = true;
_gendersList = new List<SelectListItem>()
{
new SelectListItem { Text = Constants.Gender.Boy, Value = Constants.Gender.Boy},
new SelectListItem { Text = Constants.Gender.Girl, Value = Constants.Gender.Girl},
};
if (ModelState.IsValid)
{
result = _student.Insert(mappedStudent);
if (result)
{
return RedirectToAction("Index");
}
else
{
TempData["Message"] = "Failed to create new student";
return View();
}
}
return View("Create");
}
}
View
#model CreateStudent
#{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-3.1.1.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
<h2>Create</h2>
#{
if (TempData["Message"] != null)
{
<h3>
#TempData["Message"].ToString()
</h3>
}
}
#{
}
#using (Html.BeginForm("Create","Student",FormMethod.Post))
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
<h4>Student</h4>
<hr />
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
#Html.LabelFor(model => model.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MiddleName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.MiddleName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MiddleName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-4">
#Html.EditorFor(model => model.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Gender, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#*#Html.DropDownListFor(o=>o.Gender,Model.StudentGender, "", new { #class = "form-control" })*#
#Html.DropDownListFor(o=>o.Gender,(List<SelectListItem>)Model.Genders,"1", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.Gender, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IdNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.IdNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.IdNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.SchoolIdNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.SchoolIdNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.SchoolIdNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ServiceType, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ServiceType, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ServiceType, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Comments, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Comments, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Comments, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.IsEnabled, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
<div class="checkbox">
#Html.EditorFor(model => model.IsEnabled)
#Html.ValidationMessageFor(model => model.IsEnabled, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.FirstNameAr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.FirstNameAr, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.FirstNameAr, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.MiddleNameAr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MiddleNameAr, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MiddleNameAr, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.LastNameAr, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastNameAr, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastNameAr, "", 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-primary" />
</div>
</div>
</div>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Your view is strongly typed to a CreateStudent class and the view code is using Model.Genders collection property when you use the DropDownListFor helper method. But in your http post action, you are calling the return View() method without passing a valid CreateStudent object and in another case without populating the Genders property. So when razor executes the view code, the model value is null ( because you did not pass anything to the view)
You need to set the Genders property again before returning the posted view model back to the view.
[HttpPost]
public ActionResult Create(CreateStudent student)
{
var genderList = new List<SelectListItem>()
{
new SelectListItem { Text = Constants.Gender.Boy, Value = Constants.Gender.Boy},
new SelectListItem { Text = Constants.Gender.Girl, Value = Constants.Gender.Girl},
};
if (ModelState.IsValid)
{
var result = _student.Insert(mappedStudent);
if (result)
{
return RedirectToAction("Index");
}
else
{
student.Genders = genderList;
TempData["Message"] = "Failed to create new student";
return View(student); // Passing the object here to view
}
}
//Model validation fails. Return the same view
student.Genders = genderList;
return View(student);
}
}
Also there no need for an extra casting. Model.Genders is of type List<SelectListItem>
#Html.DropDownListFor(o=>o.Gender,Model.Genders, new { #class = "form-control" })

MVC5 - View does not return the Id of my object on post

My view is shown below:
#model KtembRegistry.Models.Entities.Member
#{
ViewBag.Title = "Üye Güncelleme";
}
<h2>#ViewBag.Title</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.MemberId)
#Html.HiddenFor(model => model.Director.EmployeeId);
<div class="form-horizontal">
<hr />
<div class="form-group">
<input type="button" value="Back to List" onclick="location.href='#Url.Action("Index", "Members")'" class="btn btn-primary" />
<input type="submit" value="Save" class="btn btn-success" />
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.MemberName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MemberName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MemberName, "", 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>
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.MemberClass, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.MemberClass, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.MemberClass, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.ClassId, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.ClassId, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.ClassId, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.LastApprovalDate, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.LastApprovalDate, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.LastApprovalDate, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.TaxNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.TaxNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.TaxNo, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.Phone, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Phone, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Phone, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Fax, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Fax, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Fax, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.Mobile, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Mobile, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Mobile, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Address, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Address, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Address, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6">
<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>
</div>
<br />
<h4>Direktör</h4>
<hr />
<div class="row">
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.Director.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Director.FirstName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Director.FirstName, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Director.LastName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Director.LastName, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Director.LastName, "", new { #class = "text-danger" })
</div>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
#Html.LabelFor(model => model.Director.IdentityNo, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Director.IdentityNo, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Director.IdentityNo, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Director.Responsibility, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Director.Responsibility, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Director.Responsibility, "", new { #class = "text-danger" })
</div>
</div>
</div>
</div>
<br />
<h3> Personel </h3>
<hr />
<table class="table table-hover">
<thead>
<tr>
<th>İsim</th>
<th>Kimlik No</th>
<th>Yetki</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Employees)
{
<tr>
<td>#item.FirstName</td>
<td>#item.IdentityNo</td>
<td>#item.Responsibility</td>
<td>
#Html.ActionLink("Edit", "Edit", new { #item.EmployeeId }) |
#Html.ActionLink("Delete", "Delete", new { #item.EmployeeId })
</td>
</tr>
}
</tbody>
</table>
</div>
}
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
Entity:
public class Employee
{
public virtual int Id { get; protected set; }
public virtual int EmployeeNo { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual int IdentityNo { get; set; }
public virtual string Responsibility { get; set; }
public virtual Member Company { get; set; }
}
When I do post, everything is sent to controller just fine except model.Director.EmployeeId. The controller sends the EmployeeId field correctly to the field. Whatever, I do it does not work. Any ideas why my post does not work ?
I have an old habit of making the setter of identity fields in my entities protected in order to protect outside mangling. However, in this case it was causing the identity field from being updated which was the cause of the problem.

Categories