【问题标题】:MVC Pass generic list to controller action from JS fileMVC 将通用列表从 JS 文件传递​​给控制器​​操作
【发布时间】:2012-09-19 15:51:39
【问题描述】:

我有一个文本文件,当用户上传文件时,控制器操作方法使用状态机解析该文件并使用通用列表来存储一些值。我以隐藏字段的形式将其传递回页面。然后,用户可以单击调用 JS 模式对话框的链接,他们可以看到列表并为列表中的每个项目添加 cmets。当他们单击链接时,我试图发布到一个操作方法,该方法将采用该隐藏字段并对其进行处理并呈现部分视图。问题是当我发布到这个操作方法时,这个字段被传递为 null。

这是我的代码

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



if (Model.ExceptionString != null)
           {
               if (Model.ExceptionString.Count > 0)
               {
        <div class="bodyContent">
            <span class="leftContent">
                @Html.Label("Test Exceptions")
            </span><span class="rightContent"><span id="TestExceptionChildDialogLink" class="treeViewLink">Click
                here to View Test Exceptions</span>
                <br />
                <span id="TestExceptionDisplay"></span>
                @Html.HiddenFor(model => model.ExceptionString)
                <input id="ExceptionString" type="hidden" value="@Model.ExceptionString" />
            </span>
        </div>
               }
           }

<div id="testExceptiontreeview" title="Dialog Title" style="font-size: 10px; font-weight: normal;
    overflow: scroll; width: 800px; height: 450px;">
    <div id="testExceptions">

    </div>
    <div id="inputTestExceptions" style="display: none;">
    </div>
</div>


  var runlogTestExceptionUrl = '@Url.Action("ListTestExceptions", "RunLogEntry")';

JS FILE

 $("#inputTestExceptions").load(runlogTestExceptionUrl, { ExceptionStrings: $("#ExceptionString").val() });

控制器动作

[HttpPost]
        public ViewResult ListTestExceptions(List<string> ExceptionStrings)
        {

关于为什么异常字符串列表在由 JS 传递给 abive 操作方法时为空的任何想法?

【问题讨论】:

    标签: jquery model-view-controller


    【解决方案1】:

    $("#ExceptionString").val() 将返回一个字符串。这意味着您对 .load 的调用只是将单个名称/值对发布到您的 MVC 应用程序。

    您需要它来发布名称/值对的集合。名称将相同:带有索引器的集合的名称。该值将是异常字符串。这需要进行一些重大的重构。

    这是可以工作的基本方式:

    查看代码:

    <form action="@Url.Action("ListTestExceptions", "RunLogEntry")" TYPE="POST">
    @{ int counter = 0;}
    @foreach(var exception in Model.ExceptionString)
    {
    
      <input id='@("ExceptionString["+counter+"]")' type="hidden" value='@exception' />
      @{ counter =counter + 1; }
    }
    </form>
    

    JS代码:

    $.ajax({
            url: runlogTestExceptionUrl,
            data: $(this).serialize(),
            success: function(data) {
                 $('#inputTestExceptions').html(data);
            }
    });
    

    控制器动作不变:

    [HttpPost]
        public ViewResult ListTestExceptions(List<string> ExceptionStrings)
        {
    

    显然这不会立即与您的代码集成。但这是将数据从表单发布到 MVC 中的单个集合变量的方式。

    注意:我对 razor 语法有点生疏,所以可能存在一些小语法问题。我会在找到它们时修复它们。

    【讨论】:

      猜你喜欢
      • 2016-07-24
      • 2016-11-28
      • 2015-02-03
      • 2016-10-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-30
      • 2012-10-02
      相关资源
      最近更新 更多