Pratik Gaikwad
Pratik Gaikwad

Reputation: 1568

An optional parameter must be a reference type, a nullable type, or be declared as an optional

I am passing a value from controller to View using ViewBag and storing it in a variable. Then from the same view I am sending the value back to Controller stored in the variable. Earlier it used to work but recently it started giving me below error.

The parameters dictionary contains a null entry for parameter 'nServiceId' of non-nullable type 'System.Int32' non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult SaveRequest(Int32, BussinessObjects.class1, System.Web.Mvc.FormCollection)'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.

My code is as below:

Controller:

public ActionResult EnterData(int nServiceId)
{
    ViewBag.ServiceId = nServiceId;
    return View();
}

[HttpPost]
public ActionResult SaveRequest(int nServiceId, GetQuoteInfo viewModel, FormCollection fCollection)
{

}

View:

@{int nServiceId = ViewBag.ServiceId;}
@using (Html.BeginForm("SaveRequest",
    "MyController",
    FormMethod.Post,
    new
    {
        name = "EnterData",
        id = "EnterData",
        nServiceId = nServiceId
    }))

Upvotes: 2

Views: 6269

Answers (1)

user3559349
user3559349

Reputation:

You are not passing a value for nServiceId to the controller. You are using this overload of Html.BeginForm() where the last parameter (new { name = "EnterData", id = "EnterData", nServiceId = nServiceId }) is adding nServiceId = "nServiceId" as a html attribute, not a route value (inspect the html it generates).

You need to use this overload where the usage is

@using (Html.BeginForm("SaveRequest", "MyController", new { nServiceId = nServiceId }, FormMethod.Post, new { name = "EnterData", id = "EnterData" }))

or new { nServiceId = ViewBag.ServiceId }

Upvotes: 3

Related Questions