MVC通过单击按钮将视图传递给控制器

时间:2016-06-14 12:59:11

标签: asp.net-mvc parameter-passing

以下是我的观点:

@foreach (var item in Model)
{
    if(i == 0)
    {
        @:<div class="row">
    }
    <div class="col-md-3 col-xs-12" style="margin-top:20px;">
        @Html.ActionLink(item.Name, "ClientDetail", "Client", null, new { @class = "btn btn-primary btn-block", id = @item.id})

    </div>
    i++;
    if(i%4 == 0)
    {
        @:</div>
        i = 0;
    }
}

这是控制器:

public ActionResult ClientDetail(int id)
{        
    ClientModel model = cserv.Get(id, User.Identity.GetUserId());
    ClientViewModel viewModel = new ClientViewModel(model);
    return View(viewModel);    
}

每次点击我的某个链接时,都会出现此错误:

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

为什么我的id参数没有传递给控制器​​?

谢谢!

2 个答案:

答案 0 :(得分:1)

您希望将ID放在 routeValues 参数中。

@Html.ActionLink(item.Name, "ClientDetail", "Client", 
   new { id = item.id}, 
   new { @class = "btn btn-primary btn-block"})

相同
@Html.ActionLink(item.Name, "ClientDetail", "Client", 
    routeValues: new { id = item.id }, 
    htmlAttributes: new { @class = "btn btn-primary btn-block" })

答案 1 :(得分:1)

更改此行:

@Html.ActionLink(item.Name, "ClientDetail", "Client", null, new { @class = "btn btn-primary btn-block", id = @item.id})

为:

@Html.ActionLink(item.Name, "ClientDetail", "Client", new{ id= item.Id }, new { @class = "btn btn-primary btn-block"})

你用过的那个设置了HTML的id属性。它不是路由的ID。