I’ve used a ViewModel to represent two entities in my database, “Categories” & “Manufacturers”, because I want them as drop down list.
I’ve managed to create sound and working drop down lists of them both.
Here’s the ViewModel:
public class New_Product_View_Model
{
public int SelectedManufacturerID { get; set; }
public SelectList Manufacturers { get; set; }
public int SelectedCategoryID { get; set; }
public SelectList Categories { get; set; }
}
Here’s the [HttpGet] Controller Action:
public ActionResult Insert_New_Product()
{
var dbcontext = new LNQ2SQLDataContext();
var CatQ = from P in dbcontext.Categories
where P.SUB_CAT == null
select P;
var ManQ = from P in dbcontext.Manufacturers
select P;
var VM = new New_Product_View_Model();
VM.Categories = new SelectList(CatQ, "CAT_ID", "CAT_Name");
VM.Manufacturers = new SelectList(ManQ, "MAN_ID", "MAN_Name");
//Passes the 'VM' to the view
return View(VM);
}
AND the View I have looks like this :
@model MyAppName.ViewModels.New_Product_View_Model
@using (Html.BeginForm(FormMethod.Post))
{
@Html.DropDownListFor(m => m.SelectedCategoryID, Model.Categories, "-- Select a category --")
<br />
@Html.DropDownListFor(m => m.SelectedManufacturerID, Model.Manufacturers, "-- Select a manufacturer --")
<input type="submit" value="Add New Product" />
}
Everything work absolutely fine so far
Now here’s the [HttpPost] ActionResult :
[HttpPost]
public ActionResult Insert_New_Product(New_Product_View_Model NPVM)
{
//A few things here
//then
return View();
}
When I click the submit button in the page, I get this error:
And as far as I know, it’s because the Model in the view is null when the HttpPost method runs. Because the return in the HttpPost action, doesn’t have an instance of New_Product_View_Model.
It’s silly because I don’t want to pass any models to the view AGAIN!
I just want the same page to be available in case I need to add more products.
I tried to exchange the return with this one:
return View(new New_Product_View_Model());
But I get this error:
See the picture here
I also tried this:
NPVM = new New_Product_View_Model();
return View(NPVM);
But just got the same error.
Does anyone have any solution ?
I’d really appreciate any help.
HTTP is stateless and MVC is a beautyful example of a being a Statless Loving web development framework. each request is like new. So you should repopulate the Collection properties when you send the model back to the view.
Consider using the PRG (Post-Redirect-GET) pattern. That means , If your transaction (Save to DB) is successful, you should do a Redirect to a
Getaction to show the new productAssuming
GetCategories()andGetManufacturersmethod returns a SelectList of Your Categories and Manufacturers, which you can use to bind the drop downs in your view.