Reputation: 997
I have a Create Action in my Controller. The Get Version Initializes the Model that is bound to the Form in the View Like Below.
public ActionResult Create(int someId)
{
AppDbContext = new ApplicationDbContext();
ItemViewModel model = new ItemViewModel()
{
SomeId = someId
};
return View(model);
}
And the post Method as
[HttpPost]
public async Task<ActionResult> Create(int someId, ItemViewModel model)
{
//Some Code Here
return View(model);
}
The issue is I get an error:
The parameters dictionary contains a null entry for parameter 'someId' of non-nullable type 'System.Int32' for method 'System.Threading.Tasks.Task`1[System.Web.Mvc.ActionResult] Create(Int32, SomeSystem.ViewModels.Admin.Some.SomeViewModel)' in 'SomeSystem.Controllers.SomeController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters
Although My URL before posting looks like:
SomeController/Create?someId=14
I have also tried having :
[HttpPost]
public async Task<ActionResult> Create(ItemViewModel model)
{
var myvar = model.SomeId; //SomeId is Null.
//Some Code Here
return View(model);
}
I am assuming, the values I have initialized in the Get Method of the Create Action, should be available at the post; but for they are not.
EDIT: My View just a form:
@model AuctionSystem.ViewModels.Admin.Item.ItemViewModel
@using (Html.BeginForm("Create", "AdminItem", FormMethod.Post, new { @class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))
{
//HTML Helpers for Text boxes
//Submit Button
}
Upvotes: 3
Views: 5140
Reputation: 5014
You need to put someId
in the form so it gets sent to the controller method. This won't happen automatically. You should go with the second thing you tried, putting SomeId in the model, then put this inside your form:
@Html.HiddenFor(m => m.SomeId)
Html.HiddenFor
is a helper method which creates a hidden HTML input element. When you pass in the lambda expression m => m.SomeId
, the input is given the value of that property from the model and a name which MVC uses to bind to your model in the controller method when the form is submitted. This allows someId
to be sent back to the server along with the user's input when they submit the form.
In this case, the HTML it generates will be something like this (excluding some validation attributes):
<input type="hidden" value="14" name="SomeId" />
Upvotes: 7