本文介绍了ASP.NET MVC返回逗号分隔的字符串从从ListBoxFor到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个ListBoxFor返回一个逗号分隔的字符串,并将其保存到我们的数据库。我稍后在程序上使用这一点,掰开字符串。

I am trying to get a comma delimited string returned from a ListBoxFor and save it into our database. I use this later on in the program and break apart the string.

下面是我:

型号:

public string Mask_Concat { get; set; }

查看:

<div class="fancy-form" id="mainMask">
    @Html.LabelFor(model => model.Mask_Concat, "Mask(s)", new { @class = "control-label col-md-2" })
    <div class="col-md-12">
        @Html.ListBoxFor(model => model.Mask_Concat, Enumerable.Empty<SelectListItem>(), new { @class = "chosen-container chosen-container-multi", @style = "width:300px" })
        @Html.ValidationMessageFor(model => model.Mask_Concat, "", new { @class = "text-danger" })
    </div>
</div>

控制器:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "Mask_Concat")] Chip_Master chipMaster)
{
    if (ModelState.IsValid)
    {
        db.Chip_Master.Add(chipMaster);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(chipMaster);
}

目前,我只回了多选的第一个值。
例:ListBoxFor填充了掩码1,MASK2,MASK3,mask4,mask5

Currently, I am only returning the first value in the multi-select.Example: ListBoxFor is populated with mask1, mask2, mask3, mask4, mask5.

掩码1和mask5被选择的创建。

mask1 and mask5 are selected on the create.

当Mask_Concat使它回到控制器,只有MASK1传递

When Mask_Concat makes it back to the controller, only mask1 is passed.

我如何可以传递值MASK1,mask5?

How can I pass the values as mask1,mask5?

推荐答案

在你的HTML添加一个隐藏字段:

On your HTML add a hidden field:

<input type="hidden" id="selectedValues" name="selectedValues"/>

一类添加到您的ListBoxFor

Add a class to your ListBoxFor

@Html.ListBoxFor(model => model.Mask_Concat, Enumerable.Empty<SelectListItem>(), new { @class = "chosen-container chosen-container-multi change-select", @style = "width:300px"})

这里的的onchange方法(jQuery的):

Here's the onchange method(jquery):

<script type="text/javascript">
     $('select .change-select').change(function () {
        var $hidden = $("#selectedValues");
        $hidden.val($(this).find('option:selected').map(function () {
            return $(this).val();
        }).get().join(", "));
    });
</script>

您的控制器将会是这样的:

Your controller is going to look like this:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Chip_Master chipMaster)
{
    if (ModelState.IsValid)
    {
        chipMaster.Mask_Concat = Request.Form["selectedValues"];
        db.Chip_Master.Add(chipMaster);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(chipMaster);
}

这篇关于ASP.NET MVC返回逗号分隔的字符串从从ListBoxFor到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 03:31