C# 参数字典包含不可为空类型“System.Int32”的参数“id”的空条目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18052813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 11:09:20  来源:igfitidea点击:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

c#asp.net-mvc

提问by

I am building My first MVC application, I have a table in database containing 3 columns:

我正在构建我的第一个 MVC 应用程序,我在数据库中有一个包含 3 列的表:

  1. Id → primary key
  2. Username
  3. password
  1. id → 主键
  2. 用户名
  3. 密码

When I am clicking on edit link edit a record, its throwing following exception:

当我点击编辑链接编辑记录时,它抛出以下异常:

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Edit(Int32)' in 'MvcApplication1.Controllers.UserController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters

对于“MvcApplication1.Controllers.UserController”中的方法“System.Web.Mvc.ActionResult Edit(Int32)”的不可为空类型“System.Int32”的参数“id”,参数字典包含一个空条目。可选参数必须是引用类型、可为空类型或声明为可选参数。参数名称:参数

Here is my edit code:

这是我的编辑代码:

public ActionResult Edit(int id, User collection)
{
    UserDBMLDataContext db = new UserDBMLDataContext();
    var q = from abc in db.User_Login_Details
            where abc.Id == id
            select abc;

    IList lst = q.ToList();

    User_Login_Details userLook = (User_Login_Details)lst[0];

    userLook.Username = collection.UserName;
    userLook.Password = collection.Password;
    db.SubmitChanges();
    return RedirectToAction("Index");                  
}

采纳答案by Simon Whitehead

You are expecting an idparameter in your URL but you aren't supplying one. Such as:

您希望id在您的 URL 中有一个参数,但您没有提供。如:

http://yoursite.com/controller/edit/12
                                    ^^ missing

回答by Wouter de Kort

This error means that the MVC framework can't find a value for your idproperty that you pass as an argument to the Editmethod.

此错误意味着 MVC 框架找不到id您作为参数传递给Edit方法的属性的值。

MVC searches for these values in places like your route data, query string and form values.

MVC 在路径数据、查询字符串和表单值等位置搜索这些值。

For example the following will pass the idproperty in your query string:

例如,以下内容将id在您的查询字符串中传递该属性:

/Edit?id=1

A nicer way would be to edit your routing configurationso you can pass this value as a part of the URL itself:

更好的方法是编辑您的路由配置,以便您可以将此值作为 URL 本身的一部分传递:

/Edit/1

This process where MVC searches for values for your parameters is called Model Binding and it's one of the best features of MVC. You can find more information on Model Binding here.

MVC 为您的参数搜索值的这个过程称为模型绑定,它是 MVC 的最佳功能之一。您可以在此处找到有关模型绑定的更多信息。

回答by Rune

You get that error because ASP.NET MVC cannot find an id parameter value to provide for the id parameter of your action method.

您收到该错误是因为 ASP.NET MVC 找不到为您的操作方法的 id 参数提供的 id 参数值。

You need to either pass that as part of the url, ("/Home/Edit/123"), as a query string parameter ("/Home/Edit?id=123") or as a POSTed parameter (make sure to have something like <input type="hidden" name="id" value="123" />in your HTML form).

您需要将其作为 url 的一部分 ("/Home/Edit/123")、作为查询字符串参数 ("/Home/Edit?id=123") 或作为 POSTed 参数(确保具有类似于<input type="hidden" name="id" value="123" />您的 HTML 表单中的内容)。

Alternatively, you could make the idparameter be a nullable int (Edit(int? id, User collection) {...}), but if the id were null, you wouldn't know what to edit.

或者,您可以将id参数设为可为空的 int ( Edit(int? id, User collection) {...}),但如果 id 为空,您将不知道要编辑什么。

回答by Andrew Backer

Is the action method on your form pointing to /controller/edit/1?

表单上的操作方法是否指向/controller/edit/1

Try using one of these:

尝试使用以下之一:

// the null in the last position is the html attributes, which you usually won't use
// on a form.  These invocations are kinda ugly
Html.BeginForm("Edit", "User", new { Id = Model.Id }, FormMethod.Post, null)

Html.BeginForm(new { action="Edit", controller="User", id = Model.Id })

Or inside your form add a hidden "Id" field

或者在您的表单中添加一个隐藏的“Id”字段

@Html.HiddenFor(m => m.Id)

回答by Ramkumar Thangavel

in your WebApiConfig>> Register ()You have to change to

在您的 WebApiConfig>>Register ()您必须更改为

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }

Here the routeTemplate, is added with {action}

这里routeTemplate, 添加了{action}

回答by Corby

Just in case this helps anyone else; this error can occur in Visual Studio if you have a View as the open tab, and that tab depends on a parameter.

以防万一这对其他人有帮助;如果您有一个视图作为打开的选项卡,并且该选项卡取决于参数,则 Visual Studio 中可能会发生此错误。

Close the current view and start your application and the app will start 'Normally'; if you have a view open, Visual Studio interprets this as you want to run the current view.

关闭当前视图并启动您的应用程序,应用程序将“正常”启动;如果您打开了一个视图,Visual Studio 会将其解释为您想要运行当前视图。

回答by Aneeq Azam Khan

Just change your line of code to

只需将您的代码行更改为

<a href="~/Required/[email protected]">Edit</a>

from where you are calling this function that will pass corect id

从您调用此函数的位置,该函数将传递 corect id

回答by Alin Ciocan

I had the same error, but for me, the issue was that I was doing the request with a wrong GUID. I missed the last 2 characters.

我有同样的错误,但对我来说,问题是我使用错误的 GUID 执行请求。我错过了最后两个字符。

360476f3-a4c8-4e1c-96d7-3c451c6c86
360476f3-a4c8-4e1c-96d7-3c451c6c865e

回答by anirudh talluri

Just add Attribute routing if it is not present in appconfig or webconfig

如果 appconfig 或 webconfig 中不存在,只需添加属性路由

config.MapHttpAttributeRoutes()

回答by Nitish Saini

I also had same issue. I investigated and found missing {action} attribute from route template.

我也有同样的问题。我调查并发现路由模板中缺少 {action} 属性。

Before code (Having Issue):

代码之前(有问题):

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

After Fix(Working code):

修复后(工作代码):

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );