Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

c# - "The parameters dictionary contains a null entry for parameter" - How to fix?

I am trying to implement an edit page in order administrator to modify data in database.Unfortunately I am encountering an error.

The code below:

public ViewResult Edit(int productId) {
       // Do something here 
}

but I am getting this error:

"The parameters dictionary contains a null entry for parameter 'productId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ViewResult Edit(Int32)' in 'WebUI.Controllers.AdminController'. To make a parameter optional its type should be either a reference type or a Nullable type.
Parameter name: parameters"

I changed my route in Global.asax.cs like this:

 routes.MapRoute(
"Admin",
"Admin/{action}/{ productId}",
new { controller = "Admin", action = "Edit",  productId= "" }
);

but still I am getting the error .

question from:https://stackoverflow.com/questions/2500021/the-parameters-dictionary-contains-a-null-entry-for-parameter-how-to-fix

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That empty string for productId (in your default route) will get parsed to a null entry by the Framework, and since int does not allow null...you're getting the error.

Change:

public ViewResult Edit(int productId)

to

public ViewResult Edit(int? productId)

if you want to allow for the caller to not have to pass in a product id, which is what it looks like what you want to do based on the way your route is configured.

You could also re-configure your default route to pass in some known default for when no productId is supplied:

routes.MapRoute( 
    "Admin", 
    "Admin/{action}/{ productId}", 
    new { controller = "Admin", action = "Edit",  productId= -1 } 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...