Asp.net 使用“选定”如何将选定值的数组作为字符串发布回控制器

Asp.net 使用“选定”如何将选定值的数组作为字符串发布回控制器,asp.net,arrays,asp.net-mvc,asp.net-mvc-5,http-post,Asp.net,Arrays,Asp.net Mvc,Asp.net Mvc 5,Http Post,在将选定选项中的所有选定选项发回模型时遇到困难 鉴于: <select id="GridRegions" multiple name="@Html.NameFor(model => model.GridRegions)"> <option value=""></option> <option value="Centre">Centre</option> <option value="Inner">

在将选定选项中的所有选定选项发回模型时遇到困难

鉴于:

<select id="GridRegions" multiple name="@Html.NameFor(model => model.GridRegions)">
    <option value=""></option>
    <option value="Centre">Centre</option>
    <option value="Inner">Inner</option>
    <option value="Outer">Outer</option>
</select>
Console正确地写出所选值,例如,中心、内部,但只有中心在表单post中传回,因为字段需要单个字符串。我已经跟随了很多例子,比如如何在脚本中将数组转换为字符串,但它总是以某种方式出错

获取值数组,将其转换为逗号分隔的字符串并将其作为GridRegions的值传递给模型的最佳方法是什么?我使用的是实体框架6,因此GridRegions元素是放坡模型的一部分:

[HttpPost]
public ActionResult Form(Grading grading)
{
    if (ModelState.IsValid)
    {
        db.Gradings.Add(grading);
        db.SaveChanges();
    }
}

使用ajax,您可以将参数作为字符串数组添加到控制器操作中

[HttpPost]
public ActionResult FooAction(string[] selectedValues )
{ 
    //do stuff
    return View();
}
首先将选定值读入对象,如下所示:

var selectedValues = [];
$(".GridRegions :selected").each(function() {
  selectedValues.push($(this).attr('value'));
});
   $.post("/controller/FooAction", { selectedValues  : selectedValues  });
然后按如下方式发送:

var selectedValues = [];
$(".GridRegions :selected").each(function() {
  selectedValues.push($(this).attr('value'));
});
   $.post("/controller/FooAction", { selectedValues  : selectedValues  });

我终于找到了解决这个问题的办法,也许不是最好的解决办法,但至少它对我有效,可能会帮助其他人。最后,我给了选择列表一个替代名称,并将数据传回模型外的操作,如下所示:

ICollection<string> Grids

唯一需要注意的是,您不能基于模型中这些字段的数据注释进行验证检查,因为当执行ModelState.IsValid检查时,实际的模型字段为空,因此必须在操作中进行其他检查。

此特定表单上有14个选择元素,因此,我必须将14个不同的数组以及模型的其余部分传回控制器,然后我仍然必须将它们转换为字符串,并在保存之前将它们添加到模型中。在脚本块内进行转换以便将其作为模型的一部分传回不是更好吗?@user3632714是的,您可以添加一个以数组为属性的模型,然后仍然使用上面的方法发送它们。让我知道,我可以更新问题。将您的模型添加到问题中。