如何将Dropdownlist中的SelectedItem添加到使用模型List <>

时间:2018-10-31 07:12:52

标签: c# .net list asp.net-mvc-5 ienumerable

我正在处理一个页面,该页面将使用onclick按钮将下拉列表中的选定项目添加到列表中。

问题是新的selecteditem会覆盖旧值。

我只是想显示来自所选项目的表格,如下所示:

#---Model-----Remove-----
1   Model#1       x
2   Model#2       x
3   Model#3       x
4   Model#4       x
5   Model#5       x
-------------------------

请在下面查看我的代码

ModelDescription.cs (模型):

 public class ModelDescription
{
    public string modelDesc { get; set; }
}

控制器中的方法:

public ActionResult StockOnHand()
    {
        bindModelDesc();
        return View();
    }

 public void bindModelDesc()
    {
        var mc = db.ModelMaster_tbl.ToList();
        List<SelectListItem> mclist = new List<SelectListItem>();
        mclist.Add(new SelectListItem { Text = "--Select Model Type--", Value = "0" });
        mclist.Add(new SelectListItem { Text = "--Select All Model--", Value = "1" });

        foreach (var m in mc.Select(x => x.modelDesc).Distinct())
        {
            mclist.Add(new SelectListItem { Text = m, Value = m });

            ViewBag.ModelDescs = mclist;
        }
    }

   public ActionResult AddToListSOH(ModelDescription model)
    {
        var result = new List<ModelDescription>();
        var res = db.ModelMaster_tbl.Where(x => x.modelDesc == model.modelDesc).SingleOrDefault();

        result.Add(new ModelDescription { modelDesc = res.modelDesc });

        return PartialView("AddToListSOH", result);
    }

StockOnHand.cshtml(视图):

@using (Html.BeginForm("StockOnHand", "PWSupermarket", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.AntiForgeryToken()
<div class="card">
    <div class="card-body">
        <form class="form-horizontal" role="form">
            <h5 class="card-title">Stock On Hand</h5>
            <p class="card-text">Generates the buildable quantity of a unit. </p>
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })

            @if (TempData["Message"] != null)
            {
                <span class="text-success"><strong>@TempData["Message"]</strong></span>
            }

            <div class="form-group">
                @Html.LabelFor(model => model.modelDesc, htmlAttributes: new { @class = "col-md-3 control-label" })
                <div class="col-md-10">
                    @Html.DropDownListFor(model => model.modelDesc, ViewBag.ModelDescs as List<SelectListItem>, htmlAttributes: new { @class = "form-control" })
                    <button class="btn btn-outline-primary mt-1" type="button" onclick="AddToList()">Add To List</button>
                </div>

            </div>

            <div id="foo1" class="mt-2">

            </div>

        </form>
    </div>
</div>
}

用于渲染所选项目列表的Javascript部分视图:

  <script type="text/javascript">

     function AddToList() {
        $.ajax({
            type: "Get",
            url: '@Url.Action("AddToListSOH", "PWSupermarket")',
            data: { modelDesc: $('#modelDesc').val() },
            contentType: "application/html; charset=utf-8",
            success: function (result) {
                $('#foo1').html(result);
            },
            error: function (ex) { alert('failed.'); }
        })
    }

</script>

< strong> AddToListSOH.cshtml(选定项目列表的局部视图):

@model IEnumerable<MESProject_P1_csmvc.Models.ModelDescription>

<div>
@{ var count = 0;}
<table class="table table-sm table-striped" @*style="font-size: .7rem;"*@>
    <caption>List of Models</caption>
    <thead class="thead-dark">
        <tr>
            <th>#</th>
            <th>Model</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>
                   @count
                </td>
                <td>
                    @Html.DisplayFor(i => item.modelDesc)
                </td>
            </tr>

        }
    </tbody>
</table>
</div>

screen shot of the page

2 个答案:

答案 0 :(得分:0)

制作SelectListItem列表的示例

private List<SelectListItem> ModelDeskList(ModelDesk modelDesc)
        {
            List<SelectListItem> selectList = new List<SelectListItem>();
            selectList.Add(new SelectListItem { Value = "", Text = "------Select-----",Selected=true });
            foreach (var model in modelDesc)
            {
                selectList.Add(new SelectListItem { Value = model.Id.ToString(), Text = model.Name});
            }
            return selectList;
}

希望您能从中找到解决方案

答案 1 :(得分:0)

由于此链接,我解决了我的问题:

  

我将电子邮件列表存储在Session [“ emails”]中,每当我向列表中添加新电子邮件时,我都会对其进行更新,并将其传递给具有所有记录的新列表,并在最后返回部分视图。

.NET use partial view multiple times @Rolando F

我更改了一些代码:

ModelDescription.cs

public class ModelDescription
{
    public IEnumerable<string> modelsAdded { get; set; }
}
控制器中的

AddToListSOH方法:

 public ActionResult AddToListSOH(string model)
    {
        if (Session["modelInputs"] == null)
        {
            List<string> temphandler1 = new List<string>();
            temphandler1.Add(model);
            Session["modelInputs"] = temphandler1;
        }
        else
        {
            List<string> temphandler2 = new List<string>();
            temphandler2 = (List<string>)Session["modelInputs"];
            temphandler2.Add(model);
            Session["modelInputs"] = temphandler2;
        }

        var result = new ModelDescription { modelsAdded = (List<string>)Session["modelInputs"] }; 


        return PartialView("AddToListSOH", result);
    }

AddToListSOH.cshtml(部分视图):

<table class="table table-sm table-striped" @*style="font-size: .7rem;"*@>
    <caption>List of Models</caption>
    <thead class="thead-dark">
        <tr>
            <th>#</th>
            <th>Model</th>
            <th>Remove</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model.modelsAdded)
        {
            <tr>
                <td>
                   @count
                </td>
                <td>
                    @Html.DisplayFor(i => item)
                </td>
                <td>
                    Remove
                </td>
            </tr>

        }
    </tbody>
</table>