Partial view is return NULL on POSTBACK - asp.net-mvc-4

My partial view is returning Null on submitting the form
The main view is not null, it contains values on the form submission, I'm using render partial to include the partial view. Passing the model to partial view as well, tried passing the model in partial view action result as well but the result was the same. Any help would be highly appreciated
Thanks
View
``` <div class="container">
#using (Html.BeginForm("Menu", "Booking", FormMethod.Post))
{
#Html.AntiForgeryToken()
<fieldset class="scheduler-border">
#*<div id="">
<input type="text" id="checkduplication" style="background: white; outline: none; border: none; border-color: transparent; color: red; font-weight: bold;" disabled />
</div>*#
<div class="form-group row">
#Html.HiddenFor(model => model.MenuID)
<label class="control-label col-sm-2"> Menu Name </label>
<div class="col-sm-4">
#Html.TextBoxFor(model => model.MenuName, new { #class = " form-control", #id = "FunctionName" })
#Html.ValidationMessageFor(model => model.MenuName)
</div>
<label class="control-label col-sm-2"> Menu Price </label>
<div class="col-sm-4">
#Html.TextBoxFor(model => model.MenuPrice, new { #class = " form-control", #id = "FunctionName" })
#Html.ValidationMessageFor(model => model.MenuPrice)
</div>
</div>
<div id="MyPartialContainer">
#if (Model.MenuItems != null)
{
foreach (var x in Model.MenuItems)
{
{ Html.RenderPartial("menuitems", x); }
}
}
</div>
<div class="row" style="float: right">
<input type="submit" id="submit" title="Save" value="Save" class="btn-success btn-lg" />
<input type="button" onclick="window.location.reload();" id="cancel" title="Cancel" value="Cancel" class="btn-cancel btn-lg" />
<br /> <br />
</div>
</fieldset>
}
</div> ```
Model Classes
``` public class VMMenu
{
public VMMenu()
{
MenuItems = new List<VMMenuItems> { new VMMenuItems() };
}
public int MenuID { get; set; }
public string MenuName { get; set; }
public string MenuPrice { get; set; }
//public int BookingDetailID { get; set; }
//public int PaymentDetailID { get; set; }
public IList<VMMenuItems> MenuItems { get; set; }
}
public class VMMenuItems
{
public int MenuItemID { get; set; }
public int? MenuID { get; set; }
public string ItemName { get; set; }
public string ItemPrice { get; set; }
public int? ItemCategory { get; set; }
public string ItemCategoryName { get; set; }
} ```
Action Methods
public ActionResult Menu() {
VMMenu menu = new VMMenu();
return View(menu);
}
[HttpPost]
public ActionResult Menu(VMMenu _MenuDetails)
{
if (ModelState.IsValid)
{
VMMenu VMMenu=new VMMenu();
Mapper.CreateMap<VMMenu,Menu>();
Mapper.CreateMap<VMMenuItems,MenuItem>();
Menu obj = Mapper.Map<VMMenu, Menu>(_MenuDetails);
BookingRepo _repo = new BookingRepo();
_repo.CreateMenu(obj);
return View();
}
return View();
}
public ActionResult menuitems()
{
return PartialView();
}

Related

MVC checkbox list bounding to model

I am trying to collect all the options that the user have selected for a checkbox list. The checkbox list is built using a foreach loop and I have a int[] that I am trying to put the id into. Any help would be great.
View
#{
int idxFormats = 0;
foreach (var item in Model.ListOfFormats)
{
<div class='col-md-6'>
<input type="checkbox" value=#item.Value name="chkFormat" />
<label asp-for=#item.Selected>#Html.Raw(#item.Name)</label>
#Html.HiddenFor(m => Model.selectedFormats[idxFormats]);
</div>
idxFormats++;
}
#Html.ValidationMessageFor(model => model.selectedFormats[idxFormats])
}
Model
public List<GenericValues> ListOfFormats { get; set; }
[Display(Name = "At least one 'Format' must be selected")]
public int[] selectedFormats { get; set; }
Change the Checkbox name to selectedFormats
<input type="checkbox" value=#item.Value name="selectedFormats" />
Test example:
Model:
public class Test
{
public List<GenericValues> ListOfFormats { get; set; }
public int[] selectedFormats { get; set; }
}
public class GenericValues
{
public int Value { get; set; }
public string Name { get; set; }
public bool Selected { get; set; }
}
View:
#model Test
#{
ViewData["Title"] = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h1>Index</h1>
<form method="post">
#{
foreach (var item in Model.ListOfFormats)
{
<div class='col-md-6'>
<input type="checkbox" value=#item.Value name="selectedFormats" />
<label asp-for=#item.Selected>#Html.Raw(#item.Name)</label>
</div>
}
}
<input type="submit" value="submit" />
</form>
Controller:
public IActionResult Index()
{
Test test = new Test
{
ListOfFormats = new List<GenericValues>
{
new GenericValues
{
Name = "A",
Value = 1,
},
new GenericValues
{
Name = "B",
Value = 2,
},
new GenericValues
{
Name = "C",
Value = 3,
}
}
};
return View(test);
}
[HttpPost]
public IActionResult Index(Test test)
{
return Ok();
}
Result:
if you are looking to put id as value of your idxFormats then use this code in your checkbox:
<input type="checkbox" value=#item.Value name="chkFormat" id="#idxFormats" />
Edit:
I am not so familiar with c#, I tested with minimum code :
// Replace the model correct path by yours
#model IEnumerable<WebApplication1.Models.MyModels.ListOfFormats>
#{
int idxFormats = 0;
foreach (var item in Model)
{
<div class='col-md-6'>
<input type="checkbox" value=#item.Value name="chkFormat" id="#idxFormats"/>
<label>#Html.Raw(#item.Name)</label>
</div>
idxFormats++;
}
}

How to solve empty model trouble using both Ajax.BeginForm and Html.BeginForm in MVC

I am new to MVC and stuck in passing modal to controller.
I have read many similar threads in SO, to no avail.
Here, I have a view for entering order details.
User will enter order item details (using ajax.BeginForm) and when he clicks save, whole order will be saved in backend (using Html.BeginForm). Ajax.BeginForm is working properly and passing + displaying records properly. But Html.BeginForm is passing model as nothing.
Here is my code ...
My Models
public class OrderItemsModel
{
public string SrNo { get; set; }
public int? ItemCode { get; set; }
public string ItemName { get; set; }
public Decimal? Qty { get; set; }
public Decimal? Rate { get; set; }
public Decimal? Amount { get; set; }
}
public class OrderModel
{
public string OrderNumber { get; set; }
public string OrderDate { get; set; }
public int? CustomerCode { get; set; }
public string CustomerName { get; set; }
public string Note { get; set; }
//List of items selected in Order
public List<OrderItemsModel> ItemsSelected { get; set; }
}
Extract from My View
#model OrderApplication.Models.OrderModel
#{
ViewBag.Title = "Index";
Model.ItemsSelected = ViewBag.getlist;
}
#using (Ajax.BeginForm("UpdateItemList", "Order", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "selectedtable" }))
{
<h2 style="margin-left:5%;">Order Entry</h2>
//Order No & Date
<div class="row">
<div class="col-sm-6">
<div class="col-sm-3">
#Html.LabelFor(model => model.OrderNumber, "OrderNo"):
</div>
<div class="col-sm-3">
#Html.TextBoxFor(model => model.OrderNumber, new { #class = "form-control", #readonly = "readonly" })
</div>
</div>
<div class="col-sm-6">
<div class="col-sm-3">
#Html.LabelFor(model => model.OrderDate, "Date"):
</div>
<div class="col-sm-3">
#Html.TextBoxFor(model => model.OrderDate, new { #class = "form-control" })
</div>
</div>
</div>
<br />
//Table of entries
<div id="selectedtable">
#Html.Partial("_selectTable", Model);
</div>
<br />
}
#*Main Save*#
<div class="row">
<div class="col-sm-12">
<div class="col-sm-3">
#using (Html.BeginForm("SaveData", "Order", new { order = Model, id = "loginform", #class = "justify-content-center" }))
{
<input type="submit" value="Save Order" class="btn btn-success" />
}
</div>
<div class="col-sm-3">
<input type="button" class="btn btn-success" value="Clear Form" onclick="location.href='#Url.Action("Clear", "Order")'" />
</div>
</div>
</div>
My Controller
public class OrderController : Controller
{
public List<OrderItemsModel> dd = new List<OrderItemsModel>() ;
[HttpPost]
public ActionResult SaveData(OrderModel order, string id)
{
if (order == null) //order is always Nothing
{
return View(order);
}
if (order.CustomerCode == 0)
{
return View(order);
}
return View(order);
}
}
}
You shouldn't use both Ajax.BeginForm and Html.BeginForm, as it won't work. Please, check this post as might be of help to decide which one you wish to choose:
https://forums.asp.net/t/1757936.aspx?When+to+use+Html+BeginForm+vs+ajax+BeginForm
If you still want to use Html.BeginForm, just move the using sentence to replace your Ajax.BeginForm at the top of the page, so the form covers all fields, and the model won't be empty.

How to do validation from a viewmodel

I have a model with some validations below
public class RequestABook
{
[Required(ErrorMessage = "Name Required")]
[DisplayName("Book Name")]
public string BookName { get; set; }
[Required(ErrorMessage = "Zipcode Required")]
[DisplayName("Zipcode")]
public string ZipCode { get; set; }
[Required(ErrorMessage = "Contact Name Required")]
[DisplayName("Contact Name")]
public string ContactName { get; set; }
[Required(ErrorMessage = "Email Id Required")]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
[Required(ErrorMessage = "Book Description Required")]
public string BookDescription { get; set; }
[Required(ErrorMessage = "You need to check one answer")]
public string Answer { get; set; }
}
I have a view model here
public class RequestViewModel
{
public RequestABook MyTestViewModel { get; set; }
}
I have my main page here that loads
#model BookRequestValidation.Models.RequestViewModel
#{
ViewBag.Title = "RequestABook";
}
<h2>RequestABook</h2>
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Request Book</legend>
<div class="editor-label">
#Html.LabelFor(m => m.MyTestViewModel.BookName)
</div>
<div class="editor-field">
#Html.EditorFor(m => m.MyTestViewModel.BookName)
#Html.ValidationMessageFor(m => m.MyTestViewModel.BookName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.MyTestViewModel.ZipCode)
</div>
<div class="editor-field">
#Html.EditorFor(m => m.MyTestViewModel.ZipCode)
#Html.ValidationMessageFor(m => m.MyTestViewModel.ZipCode)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.MyTestViewModel.ContactName)
</div>
<div class="editor-field">
#Html.EditorFor(m => m.MyTestViewModel.ContactName)
#Html.ValidationMessageFor(m => m.MyTestViewModel.ContactName)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.MyTestViewModel.Email)
</div>
<div class="editor-field">
#Html.EditorFor(m => m.MyTestViewModel.Email)
#Html.ValidationMessageFor(m => m.MyTestViewModel.Email)
</div>
<div class="editor-label">
#Html.LabelFor(m => m.MyTestViewModel.BookDescription)
</div>
<div class="editor-field">
#Html.EditorFor(m => m.MyTestViewModel.BookDescription)
#Html.ValidationMessageFor(m => m.MyTestViewModel.BookDescription)
</div>
<div id="HCBudget" class="validation">
<label for="budgethealth">Budget Health</label>
#Html.RadioButton("Answer", "Red")
#Html.RadioButton("Answer", "Yellow")
#Html.RadioButton("Answer", "Green")
#Html.ValidationMessageFor(m => m.MyTestViewModel.Answer)
</div>
<input type="submit" value="Request Book" />
</fieldset>
}
Question: How do you guys handle validation with models used in a viewmodel.
Before I used this in a viewmodel everything was working well. By the time I used a viewmodel
validation stopped working.
Here is what the post action looks like.
public ActionResult RequestABook()
{
return View();
}
[HttpPost]
public ActionResult RequestABook(RequestABook quote)
{
return View();
}
It would help greatly if you posted your POST action. However, generally, I can say that validation is only run on related class instances if they are non-null. So, unless a value is posted for at least one of the properties on MyTestViewModel, it will not be instantiated by the modelbinder (MyTestViewModel will be null), and validation on its properties will not be run.
You can fix this scenario by always instantiating the MyTestViewModel property, either via the constructor of your view model or, probably better, using a custom getter and setter:
Constructor
public class RequestViewModel
{
public RequestViewModel()
{
MyTestViewModel = new RequestABook();
}
...
}
Custom Getter and Setter
private RequestABook myTestViewModel;
public RequestABook MyTestViewModel
{
get
{
if (myTestViewModel == null)
{
myTestViewModel = new RequestABook();
}
return myTestViewModel;
}
set { myTestViewModel = value; }
}

How to combine two entities in one view?

I need to display the records of the student which is the Student Attempts.
It should look something like this.
https://www.dropbox.com/s/pmazbug2j8xwehe/Example.PNG (Click for image)
But this is the Question page which shows all the correct answers. For the Student Attempts page should be exactly like that only the answers/options are replaced by the answers they attempted so when it is correct, the word will be in green and the wrong ones will be in red.
For this to happen I have to retrieve 2 data from two different entities.
Below is the IQuestion table and QuestionContent is the attribute that holds the model answers and the StudentAttempts table and Answer is the attribute that holds the answers attempted by the students.
https://www.dropbox.com/s/f92f8zvk9qn1n8p/DB%20Tables.PNG (Click for image)
How do I combine those two attributes to display in a view?
StudentAttemptsController.cs
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using iStellarMobile.Models;
namespace iStellarMobile.Controllers
{
public class StudentAttemptsController : Controller
{
private istellarEntities db = new istellarEntities();
//
// GET: /StudentAttempts/
public ActionResult Index(int id)
{
var studentattempts = db.StudentAttempts.Include(s => s.activity).Include(s => s.task).Include(s => s.UserInfo).Where(s => s.StudentID == id);
return View(studentattempts.ToList());
}
//
// GET: /StudentAttempts/Details/5
public ActionResult Details(int id = 0)
{
StudentAttempt studentattempt = db.StudentAttempts.Find(id);
if (studentattempt == null)
{
return HttpNotFound();
}
return View(studentattempt);
}
//
// GET: /StudentAttempts/Create
public ActionResult Create()
{
ViewBag.ActivityID = new SelectList(db.activities, "ActivityID", "ActivityName");
ViewBag.TaskID = new SelectList(db.tasks, "TaskID", "TaskName");
ViewBag.StudentID = new SelectList(db.UserInfoes, "ID", "UserName");
return View();
}
//
// POST: /StudentAttempts/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(StudentAttempt studentattempt)
{
if (ModelState.IsValid)
{
db.StudentAttempts.Add(studentattempt);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ActivityID = new SelectList(db.activities, "ActivityID", "ActivityName", studentattempt.ActivityID);
ViewBag.TaskID = new SelectList(db.tasks, "TaskID", "TaskName", studentattempt.TaskID);
ViewBag.StudentID = new SelectList(db.UserInfoes, "ID", "UserName", studentattempt.StudentID);
return View(studentattempt);
}
//
// GET: /StudentAttempts/Edit/5
public ActionResult Edit(int id = 0)
{
StudentAttempt studentattempt = db.StudentAttempts.Find(id);
if (studentattempt == null)
{
return HttpNotFound();
}
ViewBag.ActivityID = new SelectList(db.activities, "ActivityID", "ActivityName", studentattempt.ActivityID);
ViewBag.TaskID = new SelectList(db.tasks, "TaskID", "TaskName", studentattempt.TaskID);
ViewBag.StudentID = new SelectList(db.UserInfoes, "ID", "UserName", studentattempt.StudentID);
return View(studentattempt);
}
//
// POST: /StudentAttempts/Edit/5
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(StudentAttempt studentattempt)
{
if (ModelState.IsValid)
{
db.Entry(studentattempt).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ActivityID = new SelectList(db.activities, "ActivityID", "ActivityName", studentattempt.ActivityID);
ViewBag.TaskID = new SelectList(db.tasks, "TaskID", "TaskName", studentattempt.TaskID);
ViewBag.StudentID = new SelectList(db.UserInfoes, "ID", "UserName", studentattempt.StudentID);
return View(studentattempt);
}
//
// GET: /StudentAttempts/Delete/5
public ActionResult Delete(int id = 0)
{
StudentAttempt studentattempt = db.StudentAttempts.Find(id);
if (studentattempt == null)
{
return HttpNotFound();
}
return View(studentattempt);
}
//
// POST: /StudentAttempts/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
StudentAttempt studentattempt = db.StudentAttempts.Find(id);
db.StudentAttempts.Remove(studentattempt);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
}
IQuestion.cs (Models)
namespace iStellarMobile.Models
{
using System;
using System.Collections.Generic;
public partial class IQuestion
{
public int ID { get; set; }
public Nullable<int> ActivityID { get; set; }
public Nullable<int> TaskID { get; set; }
public Nullable<int> CategoriesID { get; set; }
public Nullable<bool> Sentence { get; set; }
public string QuestionContent { get; set; }
public string ImageURL { get; set; }
public string CreatedBy { get; set; }
public Nullable<System.DateTime> CreatedOn { get; set; }
public string UpdateBy { get; set; }
public Nullable<System.DateTime> UpdateOn { get; set; }
public Nullable<int> SchoolID { get; set; }
public Nullable<int> DLevel { get; set; }
public Nullable<int> TagID { get; set; }
public virtual ActivityTask ActivityTask { get; set; }
public virtual Category Category { get; set; }
public virtual School School { get; set; }
public virtual Tag Tag { get; set; }
}
}
StudentAttempts.cs (Models)
namespace iStellarMobile.Models
{
using System;
using System.Collections.Generic;
public partial class StudentAttempt
{
public int ID { get; set; }
public Nullable<int> ActivityID { get; set; }
public Nullable<int> TaskID { get; set; }
public Nullable<int> StudentID { get; set; }
public string Answer { get; set; }
public string Score { get; set; }
public Nullable<int> Attempts { get; set; }
public string AttemptDate { get; set; }
public string CorrectAnswer { get; set; }
public virtual activity activity { get; set; }
public virtual task task { get; set; }
public virtual UserInfo UserInfo { get; set; }
}
}
Details.cshtml (StudentAttempts view)
<fieldset>
<legend>Classes</legend>
<div class="editor-label">
<h2> #Html.LabelFor(model => model.activity.ActivityName) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.activity.ActivityName)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.task.TaskName) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.task.TaskName)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.UserInfo.UserName) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.UserInfo.UserName)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.Answer) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.Answer)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.Score) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.Score)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.Attempts) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.Attempts)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.AttemptDate) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.AttemptDate)
</div>
<br />
<div class="editor-label">
<h2> #Html.LabelFor(model => model.CorrectAnswer) </h2>
</div>
<div class="display-field">
#Html.DisplayFor(model => model.CorrectAnswer)
</div>
</fieldset>
<br />
<p>
#Html.ActionLink("Edit", "/Edit/2",null, new { id=Model.ID, #class="classname" })
<span> </span>
#Html.ActionLink("Back", "/Index", null, new { #class="classname" })
</p>
You could just make a new class type (something like "StudentAttempsVM") that has a property for each of the classes you need (Details and Attempts). Then consolidate your Controller methods to build this object and pass it to your view.

how create dropdown in mvc 4

i have these models:
public class Product
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[Display(Name = "Ürün Adı")]
public string Name { get; set; }
[Required]
[Display(Name = "Açıklama")]
public string Description { get; set; }
[Required]
[Display(Name = "Fiyat")]
public decimal Price { get; set; }
[Required]
[Display(Name = "İndirim")]
public decimal Discount { get; set; }
[Required]
[Display(Name = "İndirim Geçerli Mi?")]
public bool IsDiscountActive { get; set; }
[Required]
[Display(Name="Ürün Var Mı?")]
public bool IsAvailable { get; set; }
[Required]
[Display(Name="Kategori")]
public Category Category { get; set; }
[Display(Name="Resim")]
public Image Image { get; set; }
[Required]
public DateTime CreatedOn { get; set; }
public DateTime ChangedOn { get; set; }
[Required]
public UserProfile CreatedBy { get; set; }
public UserProfile ChangedBy { get; set; }
public IEnumerable<SelectListItem> Categories
{
get
{
return new OnlineShoppingContext().Categories.OrderBy(c=>c.Name).ToList()
.Select(e => new SelectListItem { Text = e.Name, Value = e.Id.ToString() });
}
}
}
[Table("Category")]
public class Category
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
[Required]
[Display(Name = "Kategori Adı")]
public string Name { get; set; }
[Display(Name = "Açıklama")]
public string Description { get; set; }
[Display(Name = "Resim")]
public Image Image { get; set; }
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime CreatedOn { get; set; }
public DateTime ChangedOn { get; set; }
public UserProfile CreatedBy { get; set; }
public UserProfile ChangedBy { get; set; }
public List<Product> Products { get; set; }
}
My category controller
[Authorize(Roles = "Admin")]
public class CategoryController : Controller
{
private OnlineShoppingContext db = new OnlineShoppingContext();
//
// GET: /Category/
public ActionResult Index()
{
return View(db.Categories.ToList());
}
//
// GET: /Category/Details/5
public ActionResult Details(int id = 0)
{
Category category = db.Categories.Find(id);
if (category == null)
{
return HttpNotFound();
}
return View(category);
}
//
// GET: /Category/Create
public ActionResult Create()
{
return View();
}
//
// POST: /Category/Create
[HttpPost]
public ActionResult Create(Category category, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
string pic = Guid.NewGuid().ToString();
string path = Path.Combine(Server.MapPath("~/Content/images/"), pic + Path.GetExtension(file.FileName));
file.SaveAs(path);
Image i = new Image();
i.Path = path;
i.CreatedBy = db.UserProfiles.Where(u => u.UserId == WebSecurity.CurrentUserId).FirstOrDefault();
category.Image = i;
}
category.CreatedBy = db.UserProfiles.Where(u => u.UserId == WebSecurity.CurrentUserId).FirstOrDefault();
db.Categories.Add(category);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(category);
}
//
// GET: /Category/Edit/5
public ActionResult Edit(int id = 0)
{
Category category = db.Categories.Find(id);
if (category == null)
{
return HttpNotFound();
}
return View(category);
}
//
// POST: /Category/Edit/5
[HttpPost]
public ActionResult Edit(Category category)
{
if (ModelState.IsValid)
{
db.Entry(category).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
return View(category);
}
//
// GET: /Category/Delete/5
public ActionResult Delete(int id = 0)
{
Category category = db.Categories.Find(id);
if (category == null)
{
return HttpNotFound();
}
return View(category);
}
//
// POST: /Category/Delete/5
[HttpPost, ActionName("Delete")]
public ActionResult DeleteConfirmed(int id)
{
Category category = db.Categories.Find(id);
db.Categories.Remove(category);
db.SaveChanges();
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
create.cshtml
#model OnlineShopping.Models.Product
#{
var db = new OnlineShopping.Models.OnlineShoppingContext();
ViewBag.Title = "Create";
}
<h2>Create</h2>
#using (Html.BeginForm("Create", "Product", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Product</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Category)
</div>
<div class="editor-field">
// Error Model is null
#Html.DropDownListFor(model => model.Category, new SelectList(Model.Categories, "Value", "Text"))
#Html.ValidationMessageFor(model => model.Category)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Price)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Price)
#Html.ValidationMessageFor(model => model.Price)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Discount)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Discount)
#Html.ValidationMessageFor(model => model.Discount)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.IsDiscountActive)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.IsDiscountActive)
#Html.ValidationMessageFor(model => model.IsDiscountActive)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.IsAvailable)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.IsAvailable)
#Html.ValidationMessageFor(model => model.IsAvailable)
</div>
<div class="editor-field">
<input type="file" name="file" id="file" />
</div>
<p>
<input type="submit" value="#Translations.Common.Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink(Translations.Common.BackToList, "Index")
</div>
#section Scripts {
#Scripts.Render("~/bundles/jqueryval")
}
On create.cshtml page i got this error
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Line 19:
Line 20:
Line 21: #Html.DropDownListFor(model => model.Category, new SelectList(Model.Categories, "Value", "Text"))
Line 22: #Html.ValidationMessageFor(model => model.Category)
Line 23:
In GET your Model is null, so Model.Categories crashes. Try the following:
//
// GET: /Category/Create
public ActionResult Create()
{
var model = new OnlineShopping.Models.Product();
return View(model);
}
Your create view expected you to pass in a model, then in your view, it will look for model's value to generate dropdown list for you. As you haven't pass a model in so you get that object null reference exception.
Also, when you pass a model in, make sure it contains all the data you need to populate the dropdown list.