简体   繁体   English

参数字典包含一个 null 条目,用于不可为空类型“System.Int32”的参数“id”

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

I am building My first MVC application, I have a table in database containing 3 columns:我正在构建我的第一个 MVC 应用程序,我在数据库中有一个包含 3 列的表:

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

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'.对于“MvcApplication1.Controllers.UserController”中的方法“System.Web.Mvc.ActionResult Edit(Int32)”,参数字典包含不可为空类型“System.Int32”的参数“id”的 null 条目。 An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.可选参数必须是引用类型、可空类型或声明为可选参数。 Parameter name: parameters参数名称:参数

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");                  
}

You are expecting an id parameter in your URL but you aren't supplying one.您希望在您的 URL 中有一个id参数,但您没有提供一个。 Such as:如:

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

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}

This error means that the MVC framework can't find a value for your id property that you pass as an argument to the Edit method.此错误意味着 MVC 框架找不到您作为参数传递给Edit方法的id属性的值。

MVC searches for these values in places like your route data, query string and form values. MVC 在路径数据、查询字符串和表单值等位置搜索这些值。

For example the following will pass the id property in your query string:例如,以下内容将在您的查询字符串中传递id属性:

/Edit?id=1

A nicer way would be to edit your routing configuration so 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. MVC 为您的参数搜索值的这个过程称为模型绑定,它是 MVC 的最佳功能之一。 You can find more information on Model Binding here .您可以在此处找到有关模型绑定的更多信息。

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)

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 参数(确保具有类似于 HTML 表单中的<input type="hidden" name="id" value="123" /> )。

Alternatively, you could make the id parameter 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 为空,您将不知道要编辑什么。

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 }
        );

This might be useful for someone who has everything done right still facing issue.这对于已经完成所有事情但仍面临问题的人来说可能很有用。 For them "above error may also cause due to ambiguous reference".对他们来说“上述错误也可能因引用不明确而导致”。

If your Controller contains如果您的Controller包含

using System.Web.Mvc;

and also并且

using System.Web.Http;

It will create ambiguity and by default it will use MVC RouteConfig settings instead of WebApiConfig settings for routing .它会产生歧义,默认情况下它将使用 MVC RouteConfig设置而不是WebApiConfig设置进行routing Make sure for WebAPI call you need System.Web.Http reference only确保WebAPI调用只需要System.Web.Http引用

I was facing the Same Error.我正面临着同样的错误。

Solution: The name of the variable in the View through which we are passing value to Controller should Match the Name of Variable on Controller Side.解决方案:View 中通过其传递值给 Controller 的变量名称应与 Controller 端的变量名称匹配。

.csHtml (View) : .csHtml(查看):

@Html.ActionLink("Edit", "Edit" , new { id=item.EmployeeId })

.cs (Controller Method): .cs(控制器方法):

 [HttpGet]
            public ActionResult Edit(int id)
            {
                EmployeeContext employeeContext = new EmployeeContext();
                Employee employee = employeeContext.Employees.Where(emp => emp.EmployeeId == id).First();
                return View(employee);
            }

Make the id parameter be a nullable int:使 id 参数成为可为空的 int:

public ActionResult Edit(int? id, User collection)

And then add the validation:然后添加验证:

if (Id == null) ...

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 会将其解释为您想要运行当前视图。

Just change your line of code to只需将您的代码行更改为

<a href="~/Required/Edit?id=@item.id">Edit</a>

from where you are calling this function that will pass corect id从您调用此函数的位置,该函数将传递 corect id

I had the same error, but for me, the issue was that I was doing the request with a wrong GUID.我有同样的错误,但对我来说,问题是我使用错误的 GUID 执行请求。 I missed the last 2 characters.我错过了最后两个字符。

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

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

config.MapHttpAttributeRoutes()

If you're confused why your id is passing a null value via your razor file, I had the order of the overload wrong.如果您对为什么您的id通过您的 razor 文件传递 null 值感到困惑,我认为重载的顺序是错误的。 You don't have to worry about it being nullable in this case.在这种情况下,您不必担心它可以为空。

Example:例子:

This will NOT pass your id , since the overload is not in the correct position:这不会传递您的id ,因为重载不在正确的 position 中:

@Html.ActionLink("Edit", "Edit", "Controller", new { @class = "btn btn-primary" }, new { @id = x.Id })

This is the correct order to pass id , with html attributes after:这是传递id的正确顺序,后面有 html 个属性:

@Html.ActionLink("Edit", "Edit", "Controller", new { @id = x.Id }, new { @class = "btn btn-primary" })

@Html.ActionLink(item.Name, "Edit", new { id = item.Id }) here notice that parameters given to the ActionLink() is in order. @Html.ActionLink(item.Name, "Edit", new { id = item.Id }) 注意这里给 ActionLink() 的参数是有序的。

  1. first parameter is for the text field to show on-page.第一个参数用于在页面上显示的文本字段。
  2. second one is for action URL.第二个用于操作 URL。
  3. List one is for ID reference.清单一供ID参考。

I had the same error, but for me, the issue was that我有同样的错误,但对我来说,问题是

I need to add in Index view the following missing in details action link我需要在索引视图中添加以下详细信息操作链接中缺少的内容

new { id = item.user_id}

This is the complete code:这是完整的代码:

    @foreach (var item in Model)
 {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.user_id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.user_name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.user_password)
            </td>
    
            @Html.ActionLink("Details", "Details", new { id = item.user_id}) 
               
        </tr>
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 参数字典包含不可为空类型“System.Int32”的参数“id”的 null 条目。 - The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' . . 参数字典包含非空类型&#39;System.Int32&#39;的参数&#39;id&#39;的空条目 - The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' 参数字典包含非空类型&#39;System.Int32&#39;的参数&#39;_id&#39;的空条目 - The parameters dictionary contains a null entry for parameter '_id' of non-nullable type 'System.Int32' Create(Int32) 参数字典包含不可为空类型“System.Int32”的参数“id”的空条目 - Create(Int32) the parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' 参数字典包含非空类型为&#39;System.Int32&#39;的参数的空条目 - The parameters dictionary contains a null entry for parameter of non-nullable type 'System.Int32' 参数字典包含非空类型&#39;System.Int32&#39;的参数&#39;SolutionArchitectID&#39;的空条目 - The parameters dictionary contains a null entry for parameter 'SolutionArchitectID' of non-nullable type 'System.Int32' 参数字典包含非空类型“ System.Int32”的参数“ imageWidth”的空条目 - The parameters dictionary contains a null entry for parameter 'imageWidth' of non-nullable type 'System.Int32' 参数字典包含用于方法的非空类型&#39;System.Int32&#39;的参数&#39;userId&#39;的空条目 - The parameters dictionary contains a null entry for parameter 'userId' of non-nullable type 'System.Int32' for method 参数字典包含非可空类型&#39;System.Int32&#39;的参数&#39;testId&#39;的空条目 - The parameters dictionary contains a null entry for parameter 'testId' of non-nullable type 'System.Int32' 参数字典包含用于方法的非空类型&#39;System.Int32&#39;的参数&#39;foo&#39;的空条目 - The parameters dictionary contains a null entry for parameter 'foo' of non-nullable type 'System.Int32' for method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM