簡體   English   中英

如何將 IEnumerable(來自一個類)和普通 model 返回到視圖(來自另一個類)

[英]How to return an IEnumerable (from one class) AND normal model to a view (from another class)

我有一個從 class #1 獲取信息的下拉列表。

視圖中的下拉列表(以及視圖頂部的當前視圖 model 聲明):

@model LAB.Models.class1

@if (ViewBag.ProductGroup != null)
{
    @Html.DisplayFor(m => m.selected_product_group, 
                       new { htmlAttributes = new { @class = "form-control" } })
    @Html.DropDownListFor(m => m.selected_product_group, 
                           new SelectList(ViewBag.ProductGroup, "id", "product_group"), 
                           "Please Select", new { @class = "form-control" })
 }

根據您的 select,現在必須使用其變量填充表(在同一視圖上)。 像這樣:

<table class="table table-striped" style="width:85%" align="center">
    <tr>
        <th>
            @Html.DisplayNameFor(m => m.ID)
        </th>
        <th>
            @Html.DisplayNameFor(m => m.Name)
         </th>   
         <th>
           //field for input value
         </th> 
     </tr>
  @foreach (var item in Model)
  {
     <tr>
         <th>
             @Html.DisplayFor(modelItem => item.ID)
         </th>
         <th>
             @Html.DisplayFor(modelItem => item.Name)
         </th>
         <th>
             //field for input value
         </th>
     </tr>
   }

但是我不能在視圖中有@model IEnumerable<LAB.Models.class2>和這個@model LAB.Models.class1

我該怎么做呢?

您應該使用 partialview 和 ajax 在同一視圖中動態獲取 model。

@model LAB.Models.class1
    @if (ViewBag.ProductGroup != null)
    {
       @Html.DisplayFor(m => m.selected_product_group, new { htmlAttributes = new { @class = "form-control" } })
       @Html.DropDownListFor(m => m.selected_product_group, new SelectList(ViewBag.ProductGroup, "id", "product_group"), "Please Select", new { @class = "form-control",id="prdouctDropDown" })
    }
    <div id="selectedProductGroup">
      //selected product table on dropdown change
    </div>


@section Scripts{
  <script>
     $("#prdouctDropDown").change(function(){
        var selectedValue = this.value;
        $.get("getProduct_url",{id:selectedValue},function(result){
           if(result){
              $("#selectedProductGroup").html(result);
           }
        })
      })
  </script>
}

獲取選定的產品作為局部視圖

public ActionResult GetProduct(int id){
    var product = new List<LAB.Models.class2>()     
    return PartialView(product);    
}

所選產品局部視圖:

@model List<LAB.Models.class2>()
    <table class="table table-striped" style="width:85%" align="center">
        <tr>
            <th>
                @Html.DisplayNameFor(m => m.ID)
            </th>
            //...
        </tr>
        @foreach (var item in Model)
        {
           <tr>
             <td>
                @Html.DisplayFor(modelItem => item.ID)
             </td>
             //....
          </tr>
        }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM