【问题标题】:Cannot pass list of objects from view to controller by Ajax无法通过 Ajax 将对象列表从视图传递到控制器
【发布时间】:2020-11-24 10:45:16
【问题描述】:

我无法通过 Ajax 将对象列表传递给控制器​​。

但是我的代码很简单:

这是对象类:

    public class OptionDTO
{

    public string ID_OPTION { get; set; }       
    public string LI_VALUE { get; set; }

}

这是我的看法:

<div class="col-lg-12 col-md-12 col-xs-12" id="divOption">

<table id="TableOption">
   @foreach (var item in Model)
   {
    <tr class="item">
        <td>@item.LI_OPTION</td>
        <td>
                <input type="text" class="option-value" data-id="@item.ID_OPTION" />
        </td>
    </tr>
   }
</table>
<script>

function fctValidate() {
    var lstOption = [];
    try
    {
        $(".option-value").each(function(){
            var oOption = new Object();
            oOption.ID_OPTION = $(this).attr('data-id');
            oOption.LI_VALUE = $(this).val();
            lstOption.push(oOption);
        });
    } catch (error) {
        alert(error);
    }

    $.ajax({
        type: "POST",
        traditional: true,
        url: '@Url.Action("CreateOption", "CreateOption")',
        data: { "lstOption": lstOption },
        dataType: "json",
        error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
        }
    });
}

这里是控制器:

[HttpPost]
public void CreateOption(List<OptionDTO> lstOption)
{
   string dd = "";
}

我用值(表中的几行)填充输入“文本”。 我已经在 javascript 中检查了该列表包含几行。 当我点击验证按钮时,代码会转到控制器,但参数 lstOption 保持为空。

你能帮帮我吗?

非常感谢。

埃里克。

【问题讨论】:

  • 在视图中,你用什么做模型?
  • 只是在这里猜测:而不是data: { "lstOption": lstOption }尝试-data: lstOption
  • 您向我们展示的 OptionDTO 类中没有 LI_OPTION。所以上面的视图应该会在&lt;td&gt;@item.LI_OPTION&lt;/td&gt; 上引发错误。
  • derloopkat,Dawood Awan:谢谢您的回答。我会检查他们,我会告诉你。

标签: c# ajax asp.net-mvc


【解决方案1】:

derloopkat,达伍德·阿万: 感谢您的建议,我终于有了可行的解决方案:

 function fctValidate() {
    var lstOption = [];
    try {
        $(".option-value").each(function () {
            lstOption.push({
                ID_OPTION: $(this).data('id'),
                LI_VALUE: $(this).val()

            });
        });
    } catch (error) {
        alert(error);
    }

     $.ajax({
        type: "POST",
        url: '@Url.Action("CreateOption", "CreateOption")',
        data: { 'lstOption': lstOption },
        dataType: "json",
        error: function (xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            alert(err.Message);
        }
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    • 1970-01-01
    • 1970-01-01
    • 2015-04-28
    • 1970-01-01
    相关资源
    最近更新 更多