【问题标题】:ASP.NET MVC 5 - model value not getting passed correctlyASP.NET MVC 5 - 模型值未正确传递
【发布时间】:2014-08-12 08:40:28
【问题描述】:

我正在 MVC 5 中开发一个 Web 应用程序 - 还使用带有 Kendo UI Grid 的 Web API 来显示数据。加载汽车数据网格时,它基于将在模型上设置的客户 ID。

Kendo UI Grid 的标记位于 Partial_View 中。

所以在我的 MVC 控制器中,我有如下内容:

model.CustId = "12345"; //just hard coded - will possibly come from query string or set somewhere else
return PartialView(_CarDetails, model);

在我的 _CarDetails 部分视图中,Kendo Grid 代码如下。我还在 CustId 的部分视图中设置了 @Html.HiddenFor

@Html.HiddenFor(model => model.CustId)

                    //other setting up off Kendo UI Grid removed for Brevity
                      .DataSource(dataSource => dataSource
                          .Ajax()
                         .Read(read => read.Url("api/Car/GetDetails").Type(HttpVerbs.Get).Data("GetCustId"))
                      )
                      )
            </div>

所以在我的 Document.Ready 中加载 Partial 视图的页面上,我有一个 GetCustId 的 js 函数 - 它如下:

    function GetCustId() {
        alert('@Model.CustId');
        return { custId: '@Model.CustId' };
    }

警告它返回空白,然后如果我在 webapi 控制器中的 GetDetails 方法上设置断点,则 custId 字段为空 - 如果我将其硬编码为我的 js 函数中的某个值,它可以很好地传递,但是我的方式有什么不正确是否已将其连接起来以从模型中获取值?

更新

Web API 方法签名如下:

   public DataSourceResult GetDetails([ModelBinder(typeof(ModelBinders.DataSourceRequestModelBinder))] DataSourceRequest request, string custId)
        {
            //this is another method in web api controller that calls services to get details and then maps the responses to View Model
            return GetCarDetailsByCustId(custId).ToDataSourceResult(request);
        }

注意,我还更新了 WebAPIconfig.cs 文件以在路径中包含 {action},如下所示:

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

【问题讨论】:

  • 控制器中的动作签名是什么?
  • @DavidShorthose - 更新了问题以包含此
  • 发布您将部分视图添加到主视图的标记
  • 如果您通过 jquery 访问隐藏的值会发生什么,而不是从模型中设置值?例如 $("#CustId").val() 在你的脚本中
  • 这通常是我设置值的方式。很高兴现在一切都为您工作。

标签: c# javascript asp.net-mvc kendo-ui asp.net-mvc-5


【解决方案1】:

当模型已经绑定到视图时,不确定为什么需要隐藏字段或 js。您应该能够:

.Read(read => read.Url("api/Car/GetDetails").Type(HttpVerbs.Get).Data((string)model.CustId ))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-10-19
    • 2014-10-17
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 2015-09-25
    相关资源
    最近更新 更多