【问题标题】:ASP.NET MVC Controller not passing correct value to PartialView using ModelViewASP.NET MVC 控制器未使用 ModelView 将正确的值传递给 PartialView
【发布时间】:2013-12-05 11:34:20
【问题描述】:

我正在尝试创建一个 CustomMembershipProvider。当用户点击登录时,我想显示“欢迎UserName!”在 Shared/_layout .cshtml 中包含的 PartialView 中

这是控制器类:

    [ChildActionOnly]
    public ActionResult WelcomeMessage()
    {
        var userName = this.HttpContext.Session["LoggedInUser"];
        WelcomeViewModel wView = new WelcomeViewModel();

        if (userName != null)
        {
            User user = this.db.Users.FirstOrDefault(x => x.UserName == userName);
            wView.userId = user.Id;
            wView.Message = user.UserName;

        }
        return PartialView(wView);
    }

这里是部分视图代码:

    @model MvcApplication1.ViewModels.WelcomeViewModel
    @Html.ActionLink("Welcome " + Model.Message + "!", "Edit", "Account",  new { id = Model.userId })

我可以正确渲染视图,但是当我单击超链接时,出现以下错误:

参数字典包含“MvcApplication1.Controllers.AccountController”中方法“System.Web.Mvc.ViewResult Details(Int32)”的不可为空类型“System.Int32”的参数“id”的空条目。可选参数必须是引用类型、可空类型或声明为可选参数。

似乎使用 id = null 调用了编辑操作,但是用户名显示正确。我最初使用 ViewBag 并根据 SO 解决方案 here 切换到 ViewModel。 提前致谢。

【问题讨论】:

  • 动作是Edit or Details?

标签: asp.net-mvc


【解决方案1】:

试试这个

@Html.ActionLink("Welcome " + Model.Message + "!", "Edit", "Account", new { id = Model.userId }, null)

问题是你设置了ActionLink方法的htmlAttributes参数。

【讨论】:

    【解决方案2】:

    你打错了overload@Html.ActionLink,你需要这个one

    Html.ActionLink("Welcome " + Model.Message + "!", // Display text 
                    "Edit",   // ActionMethod
                    "Acount", // Controller Name.
                    new { Model.Id }, // Route arguments.
                    null  // htmlArguments
                   )
    

    基本上,您需要传递htmlAttributes 参数来达到正确的重载,如果您不需要设置任何参数,您可以将其传递为null

    【讨论】:

      【解决方案3】:

      看来您使用了错误的重载,试一试:

      @Html.ActionLink("Welcome " + Model.Message + "!", "Edit", "Account", 
         new { id = Model.userId }, 
         null)
      

      【讨论】:

      • @Purusartha Awesome :) 很高兴我能帮上忙
      猜你喜欢
      • 1970-01-01
      • 2010-09-14
      • 2011-01-01
      • 1970-01-01
      • 2011-12-16
      • 2015-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多