Unable to add the value from dropdownlist to database - c#

I created a form to store information about the customers and his membership type. For that I am using the drop down list to hold values for membership types. But on submitting the form, the value(Id) for membership type isnt added to database
//Model Membership Types
public int Id { get; set; }
public string Name { get; set; }
//ViewModel NewCustomerviewModel
public IEnumerable<MembershipTypes> MembershipTypes { get; set; }
public Customers Customers{ get; set; }
//Controler CustomerController
public IActionResult Index()
{
var customers = _context.Customers.Include(c => c.MembershipTypes).ToList();
return View(customers);
}
[HttpPost]// Create is the aciton for Submit Button
public IActionResult Create(Customers customers)
{
_context.Customers.Add(customers);
_context.SaveChanges();
return RedirectToAction("Index", "Customers");
}
//View Model
#model Wes.ViewModels.NewCustomerviewModel;
#Html.DropDownListFor(m => m.Customers.MembershipTypes, new SelectList(Model.MembershipTypes, "Id", "Name"),"Select Membership Type", new { #class = "form-control" })
When the Form is Submitted, it should add all the values to the database including the value of Drop Down List Membership Types

You could try doing it this way:
//model
public int Id { get; set; }
public string Name { get; set; }
public enum MembershipTypes
{
Type1,
Type2,
Type3
}
public MembershipTypes _membershipTypes {get; set; }
//controller
[HttpPost]
public IActionResult Create([Bind("Id","Name","_membershipTypes")] Customers customers)
{
if (ModelState.IsValid)
{
_context.Add(customers);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
Return View(customers);
}
//view
<div class="row">
<div class="col-md-6">
<form asp-action="Create">
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
#Html.DropDownList("_membershipTypes",
new SelectList(Enum.GetValues(typeof(MembershipTypes))),
"Select membership type",
new { #class = "form-control" })
</div>
<input type="submit" value="Submit!" />
</form>
</div>
</div>

You need to show more about the relationships(one-to-one,one-to-many) of your models.
The parameters of your post action need to correspond with the model of your view,use NewCustomerviewModel instead of Customers.
The dropdownlist shows the type of name and pass id as value to action, so your asp-for of dropdown list needs to be set for an id or id list.
Refer to my demo which pass id list of MembershipTypes to action using multiple select.
1.My ViewModel NewCustomerviewModel,
public class MembershipTypes
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class NewCustomerviewModel
{
public int[] SelectMembershipTypesId { get; set; }
public Customers Customers { get; set; }
}
public class Customers
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<MembershipTypes> MembershipTypes { get; set; }
}
2.Create GET action
public IActionResult Create()
{
var model = new NewCustomerviewModel()
{
Customers = new Customers()
{
MembershipTypes = _context.MembershipTypes.ToList()
},
};
return View(model);
}
3.Create POST action
[HttpPost]
public async Task<IActionResult> Create(NewCustomerviewModel viewmodel)
{
if (ModelState.IsValid)
{
viewmodel.Customers.MembershipTypes= _context.MembershipTypes
.Where(m =>viewmodel.SelectMembershipTypesId.Contains(m.Id))
.ToList();
_context.Add(viewmodel.Customers);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
return View(viewmodel);
}
4. Create View
#Html.DropDownListFor(m => m.SelectMembershipTypesId,
new SelectList(Model.Customers.MembershipTypes, "Id", "Name"), "Select Membership Type",
new { #class = "form-control", #multiple = "multiple" })

Related

DropdownList is giving a null value to controller calling model

I am a student developer in ASP.NET. I have a question which i did not find a solution about it. I can build a form for my controller. i am taking a value from my input objects but i am not taking value from dropdown list to my controller. It gives null value on my controller. Could you help me about where i made a mistake?
My View Model :
public class CountryViewModel
{
public IEnumerable<Country> CountryList { get; set; }
public Country Country;
}
My controller :
public ActionResult Index()
{
var model = new CountryViewModel()
{
CountryList = db.Country.ToList()
};
return View(model);
}
[HttpPost]
public ActionResult Index(string timeForCheckedOut,CountryViewModel cvModel)
{
return View();
}
my index.cshtml:
#model PenaltyCalculation.Models.ViewModel.CountryViewModel
<form class="" style="margin-top:10%;" action="/" method="post">
<div class="form-group">
<label>Check out date of the Book</label>
<input class="form-control" type="date" name="timeForCheckedOut">
</div>
<div class="form-group">
<label>Choose a country</label>
#Html.DropDownListFor(m=>m.Country.countryId,new SelectList(Model.CountryList,"countryId","countryName"),new {#class="form-control" })
</div>
<button type="submit" class="btn btn-primary">Calculate</button>
</form>
My Country Model:
public partial class Country
{
public int countryId { get; set; }
public string countryName { get; set; }
}
Option #1:
You just need to put the { get; set; } on the end of Country in your CountryViewModel. This will allow you to set the countryId value, but the name will not be set. You will have to look that up from your db if you need that also.
public class CountryViewModel
{
public IEnumerable<Country> CountryList { get; set; }
public Country Country { get; set; }
}
Option #2
This is what I would do. Remake your CountryViewModel to actually represent your View's Model.
public class CountryViewModel
{
public int CountryID { get; set; }
public DateTime TimeForCheckedOut { get; set; }
}
Then update your controller.
// Simulating a db
private List<Country> Countries;
public HomeController()
{
// Initializing sample data
Countries = new List<Country>();
Countries.Add(new Country() { countryId = 1, countryName = "USA" });
Countries.Add(new Country() { countryId = 2, countryName = "England" });
Countries.Add(new Country() { countryId = 3, countryName = "Japan" });
Countries.Add(new Country() { countryId = 4, countryName = "China" });
}
public ActionResult Index()
{
// I prefer using the ViewData Dictionary for my selectlists
ViewData["CountrySelectList"] = new SelectList(Countries, "countryId", "countryName");
return View();
}
[HttpPost]
public ActionResult Index(CountryViewModel cvModel)
{
var country = Countries.First(c => c.countryId == cvModel.CountryId);
// Do Stuff Like Saving and Updating
ViewData["CountrySelectList"] = new SelectList(Countries, "countryId", "countryName", cvModel.CountryId);
return View(cvModel);
}
And Finally update your View
#model PenaltyCalculation.Models.ViewModel.CountryViewModel
<form class="" style="margin-top:10%;" action="/" method="post">
<div class="form-group">
<label>Check out date of the Book</label>
<input class="form-control" type="date" name="timeForCheckedOut">
</div>
<div class="form-group">
<label>Choose a country</label>
#Html.DropDownListFor(m => m.CountryId, (SelectList)ViewBag.CountrySelectList, new { #class = "form-control" })
</div>
<button type="submit" class="btn btn-primary">Calculate</button>
</form>
public class CountryController : Controller
{
// GET: Country
public ActionResult Index()
{
var model = new CountryViewModel()
{
CountryList = GetCountries()
};
return View(model);
}
[HttpPost]
public ActionResult Index(CountryViewModel model)
{
model.CountryList = GetCountries();
return View(model);
}
private IEnumerable<Country> GetCountries()
{
return new Country[]
{
new Country()
{
CountryID = 1,
CountryName = "USA"
},
new Country()
{
CountryID = 2,
CountryName = "Mexico"
},
};
}
}
public class CountryViewModel
{
public IEnumerable<Country> CountryList { get; set; }
public int CountryID { get; set; }
public DateTime? TimeForCheckedOut { get; set; }
}
public partial class Country
{
public int CountryID { get; set; }
public string CountryName { get; set; }
}
<form class="" style="margin-top:10%;" action="/Country/Index" method="post">
<div class="form-group">
<label>Check out date of the Book</label>
<input class="form-control" type="date" name="TimeForCheckedOut">
</div>
<div class="form-group">
<label>Choose a country</label>
#Html.DropDownListFor(m => m.CountryID, new SelectList(Model.CountryList, "CountryID", "CountryName"), new { #class = "form-control" })
</div>
<button type="submit" class="btn btn-primary">Calculate</button>
</form>
This is working for me
Make sure CountryID has getter and setter. Also in C# public property name starts with Capital letter (by convention)
I would also suggest, don't bind Country entity directly to view. You may want to create CountryModel

How to save data from multiple selection dropdown

I started learning about the entity framework and asp.net and I wanted to use all CRUD operations.
I have Task and Category models and they are in many-to-many relationship. In my database there are 3 tables: 1.Task (it contains Id, Title, Description..), 2.Category (it contains categoryId and categoryName) and 3.TaskCategory (contains Id (taskId) and categoryId).
I managed to do everything I wanted except to add multiple categories to task using dropdown. I created dropdown, and loaded categories and I know how to add one category to task (when relation is 1:N) (asp-for="CategoryId"). For multiple selection I tried with selectedCategories (list od integers - ids) instead of CategoryId but I dont know what to do with that list. How to join category and task in TaskCategory while saving task in controller (in other words: how to save categories to task)?
AddTask.cshtml
<div class="form-group">
<label class="control-label">Category</label>
<select class="select-picker" asp-for="selectedCategories"
asp-items="#(new SelectList(Model.Categories, "CategoryId", "CategoryName"))" multiple>
</select>
</div>
<script>
...
$('.select-picker').selectpicker('toggle');
</script>
HomeController.cs
public IActionResult AddTask()
{
var categories = _categoryRepository.GetAllCategories().OrderBy(c => c.CategoryName);
var taskCategories = _taskCategoryRepository.GetAllTaskCategories().OrderBy(tc => tc.Id);
var homeViewModel = new HomeViewModel()
{
Task = null,
TaskCategory = null,
Categories = categories.ToList(),
TaskCategories = taskCategories.ToList(),
selectedCategories = new List<int>()
};
return View(homeViewModel);
}
[HttpPost]
public IActionResult AddTask(Task task, List<int> selected)
{
// foreach (var selectedCategoryId in selected)
// {
//
// }
_taskRepository.AddTask(task);
return RedirectToAction("Index");
return View();
}
This way I get Task in database, but ofcourse without any category saved.
Try to use ViewModel to handle relationships , the following is the working demo I made , you could refer to and make the modification as per your need
Many-to Many relationship between Task and Category :
public class Task
{
public int Id { get; set; }
public string Title { get; set; }
public List<TaskCategory> TaskCategories { get; set; }
}
public class Category
{
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public List<TaskCategory> TaskCategories { get; set; }
}
public class TaskCategory
{
public int CategoryId { get; set; }
public Category Category { get; set; }
public int TaskId { get; set; }
public Task Task { get; set; }
}
//DbContext
public DbSet<Task> Task { get; set; }
public DbSet<Category> Category { get; set; }
public DbSet<TaskCategory> TaskCategory { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<TaskCategory>()
.HasKey(t => new { t.CategoryId, t.TaskId });
modelBuilder.Entity<TaskCategory>()
.HasOne(pt => pt.Category)
.WithMany(p => p.TaskCategories)
.HasForeignKey(pt => pt.CategoryId);
modelBuilder.Entity<TaskCategory>()
.HasOne(pt => pt.Task)
.WithMany(t => t.TaskCategories)
.HasForeignKey(pt => pt.TaskId);
}
Create a TaskViewModel , a element posts back an array of its selected option values (which in your case will be an array of the Categories Id values). Your model needs a property to bind to. Add the following property:
public class TaskViewModel
{
public Task Task { get; set; }
public SelectList CategoryList { get; set; }
public List<int> selectedCategories { get; set; }
}
AddTask.cshtml:
#model WebApplication1.Models.Tasks.TaskViewModel
<div class="row">
<div class="col-md-4">
<form asp-action="AddTask">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Task.Title" class="control-label"></label>
<input asp-for="Task.Title" class="form-control" />
<span asp-validation-for="Task.Title" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="selectedCategories" class="control-label"></label>
<select asp-for="selectedCategories" class="form-control" asp-items="Model.CategoryList" multiple></select>
</div>
<div class="form-group">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</form>
</div>
</div>
Then in Post method , the value of selectedCategories will contain an array of CategoryId values that you selected in the view.
[HttpPost]
public IActionResult AddTask(TaskViewModel taskVM)
{
Models.Tasks.Task task = taskVM.Task;
_context.Add(task);
_context.SaveChanges();
foreach(var selectedId in taskVM.selectedCategories)
{
_context.TaskCategory.Add(new TaskCategory
{
TaskId = task.Id,
CategoryId = selectedId,
});
}
_context.SaveChanges();
return RedirectToAction("Index");
}

Returning data to a view which has a model which references other models

So I have my model
public class AgencyAll
{
public Agency Agency { get; set; }
public AgencySector AgencySector { get; set; }
public AgencyExpertise AgencyExpertise { get; set; }
}
which acts a reference to other models so I can pass these into my view
Example - Agency model
public partial class Agency
{
public int id { get; set; }
public System.DateTime created { get; set; }
public int createdby { get; set; }
public string createdbytype { get; set; }
public System.DateTime lastupdated { get; set; }
public int lastupdatedby { get; set; }
public string lastupdatedbytype { get; set; }
public bool deleted { get; set; }
public string name { get; set; }
public string address { get; set; }
}
The AgencySector and AgencyExpertise are only contain the agency id and the other id (sector or expertise) as it's a many to many relationship
Part of my view
#model AgencyAll
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<div class="form-group">
Sector:
#Html.DropDownListFor(model => model.AgencySector.sectorid, (SelectList) ViewBag.SectorList, new {#class = "form-control"})
</div>
</div>
<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12">
<div class="form-group">
Specialisation:
#Html.DropDownListFor(model => model.AgencyExpertise.expertiseid, (SelectList) ViewBag.SpecialismList, new {#class = "form-control"})
</div>
</div>
As you can see, I can call the different models fine
My problem occurs here
public ActionResult ViewData(int id)
{
ViewBag.CountyList = new SelectList(GetCountyList(), "Value", "Text");
ViewBag.SectorList = new SelectList(GetSectorList(), "Value", "Text");
ViewBag.SpecialismList = new SelectList(GetSpecialisationList(), "Value", "Text");
return View(_db.Agencies.FirstOrDefault(x => x.id == id));
}
specifically, this line; return View(_db.Agencies.FirstOrDefault(x => x.id == id));
I am trying to return the agency data for the url ViewData/(id) however as the model for the view is AgencyAll, it cannot assign the dataset to the model as the model does not refer to a table, it refers to multiple models which refer to tables. The return statement is expecting the view to have the Agency model, not AgencyAll.
I cannot figure out what I need to replace return View(_db.Agencies.FirstOrDefault(x => x.id == id)); with in order to pass the data from the class to the model which has the model of the table, to show the data,
Any help would be much appreciated.
You need to be providing the expected model to your view, which is AgencyAll. At the moment you're providing an Agency object.
Change your code to something like this:
public ActionResult ViewData(int id)
{
ViewBag.CountyList = new SelectList(GetCountyList(), "Value", "Text");
ViewBag.SectorList = new SelectList(GetSectorList(), "Value", "Text");
ViewBag.SpecialismList = new SelectList(GetSpecialisationList(), "Value", "Text");
var viewModel = new AgencyAll {
Agency = _db.Agencies.FirstOrDefault(x => x.id == id),
AgencySector = _db.AgencySectors.FirstOrDefault(),
AgencyExpertise = _db.AgencyExpertises.FirstOrDefatul()
}
return View(viewModel);
}

ViewModel with foreign key and Create action

I have a page that show details of a post and Identified users can add commented on that post.
My problems:
PostID and UserID is FK in Comment model and don't pass from view to controller
CommnetMessage is Null!!
what is wrong?
Comment Model :
public class Comment : System.Object
{
public Comment()
{
this.CommnetDate = General.tzIran();
}
[Key]
public int CommentID { get; set; }
[Required]
public string CommnetMessage { get; set; }
[Required]
public DateTime CommnetDate { get; set; }
public string UserId { get; set; }
[Key, ForeignKey("UserId")]
public virtual ApplicationUser ApplicationUser { get; set; }
public int PostID { get; set; }
[Key, ForeignKey("PostID")]
public virtual Post posts { get; set; }
}
Post Model:
public class Post : System.Object
{
public Post()
{
this.PostDate = General.tzIran();
this.PostViews = 0;
}
[Key]
public int PostID { get; set; }
public string PostName { get; set; }
public string PostSummery { get; set; }
public string PostDesc { get; set; }
public string PostPic { get; set; }
public DateTime PostDate { get; set; }
public int PostViews { get; set; }
public string postMetaKeys { get; set; }
public string PostMetaDesc { get; set; }
public string UserId { get; set; }
[ForeignKey("UserId")]
public virtual ApplicationUser ApplicationUser { get; set; }
public int CategoryID { get; set; }
[ForeignKey("CategoryID")]
public virtual Category Category { get; set; }
public virtual ICollection<Comment> commnets {get; set;}
}
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
/*Realations*/
public virtual ICollection<Comment> Comments { get; set; }
public virtual ICollection<Post> Posts { get; set; }
}
View Model:
public class PostViewModel
{
public ApplicationUser Users { get; set; }
public Post posts { get; set; }
public Category Categories { get; set; }
public IEnumerable<Comment> ListCommnets { get; set; }
public Comment Commnets { get; set; }
}
Controller:
public ActionResult Details(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var post = db.Posts.Find(id);
post.PostViews += 1;
db.SaveChanges();
if (post == null)
{
return HttpNotFound();
}
return View(new PostViewModel() { posts = post });
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Details([Bind(Include = "CommentID,CommnetMessage,CommnetDate,UserId,PostID")] Comment comment , int? id)
{
int pid = comment.PostID;
if (ModelState.IsValid)
{
db.CommentS.Add(comment);
db.SaveChanges();
TempData["notice"] = "پیغام شما با موفقیت ثبت شد.";
return RedirectToAction("success");
}
ViewBag.UserId = new SelectList(db.Users, "Id", "FirstName", comment.UserId);
ViewBag.PostID = id;
return View( new PostViewModel() { posts = db.Posts.Find(id)});
}
public ActionResult success()
{
ViewBag.Message = "از طریق فرم زیر می توانید برایمان پیغام بگذارید.";
return View("Details", new PostViewModel() { ListCommnets = db.CommentS });
}
Comment Partial View:
#using Microsoft.AspNet.Identity
#using FinalKaminet.Models
#using Microsoft.AspNet.Identity.EntityFramework
#model FinalKaminet.ViewModel.PostViewModel
#if (TempData["notice"] != null)
{
<p>#TempData["notice"]</p>
}
#if (Request.IsAuthenticated)
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
var user = manager.FindById(User.Identity.GetUserId());
using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div class="form-horizontal">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.posts.PostID)
#Html.HiddenFor(model => model.Users.Id)
<div class="form-group">
#Html.LabelFor(model => model.Users.FirstName, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#{
var name = user.FirstName + " " + user.LastName;
}
<input type="text" id="Id" value="#name" disabled="disabled" class="form-control" />
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Commnets.CommnetMessage, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.Commnets.CommnetMessage, new { htmlAttributes = new { #class = "form-control" } })
#Html.ValidationMessageFor(model => model.Commnets.CommnetMessage, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Send" class="btn btn-default" />
</div>
</div>
</div>
}
}
else
{
<p>#Html.ActionLink("Log in", "Login", "Account", new { returnUrl = Request.Url }, null)</p>
}
As #StephenMuecke stated, model of your view is PostViewModel and all editors, hidden fields are created based on your view model. For example, when you generate hidden field using #Html.HiddenFor(model => model.posts.PostID) and try to post your data MVC model binder tries to bind the value of this field to the model specified at your Action method. In your case it is Comment so , MVC model binder will try bind value of generated hidden field to Comment.posts.PostID which does not exist. To make everything work perfectly you have to use same view model as a argument of your action method:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Details(PostViewModel viewModel)
{
......
}
Also, again as #StephenMuecke sated, your view model should have only those properties which you need. For example, your PostViewModel should look like something as following:
public class PostViewModel
{
// Actually, you do not need UserId property
// as it should be retrieved inside controller
// from current user data
public string UserId { get; set; }
public string UserName { get; set; }
public int PostID { get; set; }
public string CommentMessage { get; set; }
}
Back to your action method, you have to map view model to your model:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Details(PostViewModel viewModel)
{
Comment comment = new Comment
{
CommnetMessage = viewModel.CommentMessage,
// and other properties
}
// Save your model and etc.
}

Null Reference Exception when i use navigation property in model class

I try to add new entity in database in controller action.
This is my model class
public class Product
{
public int ProductID { get; set; }
[Required(ErrorMessage = "Please enter product name")]
public string Name { get; set; }
[Required(ErrorMessage = "Please enter product model")]
public string Model { get; set; }
[Required(ErrorMessage = "Please enter product serial")]
public string Serial { get; set; }
[Required(ErrorMessage = "Please choose dealer")]
public int DealerID { get; set; }
[Required]
public Guid ClientID { get; set; }
[Required(ErrorMessage = "Please choose employee")]
public Guid EmployeeID { get; set; }
public virtual Dealer Dealer { get; set; }
public virtual Client Client { get; set; }
public virtual Employee Employee { get; set; }
[DisplayName("Commercial use")]
public bool UseType { get; set; }
}
This is actions for creating new product in database
public ViewResult Create()
{
PopulateDropDownLists();
var model = new Product();
return View(model);
}
[HttpPost]
public ActionResult Create(Product model)
{
try
{
if (ModelState.IsValid)
{
_repo.GetRepository<Product>().Add(model);
_repo.Save();
TempData["message"] = "Product was successfully created";
return RedirectToAction("List");
}
}
catch (DataException)
{
TempData["error"] =
"Unable to save changes. Try again, and if the problem persists, see your system administrator.";
return View("Error");
}
PopulateDropDownLists();
return View("Create");
}
CreateView has appropriate model type (Product type in this case). Code below
#using System.Web.Mvc.Html
#model STIHL.WebUI.Models.Product
#using (Html.BeginForm())
{
#Html.EditorFor(m => m.Name)
#Html.EditorFor(m => m.Model)
#Html.EditorFor(m => m.Serial)
<div class="form-group">
#Html.LabelFor(m => m.DealerID, "Dealer")
#Html.DropDownListFor(m => m.DealerID, new SelectList((IEnumerable)TempData["Dealers"],"DealerID", "DealerNumber"), string.Empty, new {#class = "form-control"})
#Html.ValidationMessageFor(m => m.DealerID, null, new {#class = "help-block"})
</div>
<div class="form-group">
#Html.LabelFor(m => m.EmployeeID, "Employee",new {#class = "control-label"})
#Html.DropDownListFor(m => m.EmployeeID, new SelectList((IEnumerable)TempData["Employees"],"EmployeeID", "FullName"),string.Empty, new {#class="form-control"})
#Html.ValidationMessageFor(m => m.EmployeeID, null, new {#class = "help-block"})
</div>
<div class ="ok-cancel-group">
<input class="btn btn-primary" type="submit" value="Create" />
#Html.ActionLink("Cancel", "List","Product",new {#class = "btn btn-primary"})
</div>
}
i always get null reference instead model in [HttpPost] action, but if i use ViewModel instead Model everything is ok (ViewModel code below)
public class ProductViewModel
{
public Product Product { get; set; }
}
I think it cause model class has virtual properties, but anyway i don't understand why it's ok when i use ViewModel.
Can anyone answer me?
Thx in advance.
The virtual properties won't change the outcome. The issue is that the view is written to bind to the view model, therefore accepting the model isn't going to work. If you want to use the model; then bind the view to the model.

Categories

Resources