【问题标题】:PartialView - How to pass a single object when View receives an IEnumerablePartialView - View 收到 IEnumerable 时如何传递单个对象
【发布时间】:2017-10-13 02:15:38
【问题描述】:

我有一个带有控制器的模型(机器)。控制器,它在索引操作“IActionResult”中收集机器列表并将其发送到索引视图。

public async Task<IActionResult> Index(string sortOrder, string searchString)
{
    ViewData["NameSortParm"] = string.IsNullOrEmpty(sortOrder) ? "nombre_desc" : "";
    ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";
    ViewData["CurrentFilter"] = searchString;

    var maquinas = from s in _context.Machines
                   select s;
    if (!String.IsNullOrEmpty(searchString))
    {
        maquinas = maquinas.Where(s => s.MchName.Contains(searchString));
    }
    switch (sortOrder)
    {
        case "nombre_desc":
            maquinas = maquinas.OrderByDescending(s => s.MchName);
            break;
        case "Date":
            maquinas = maquinas.OrderBy(s => s.FechaCompra);
            break;
        case "date_desc":
            maquinas = maquinas.OrderByDescending(s => s.FechaCompra);
            break;
        default:
            maquinas = maquinas.OrderBy(s => s.MchName);
            break;
    }
    return View(await _context.Machines.Include(t => t.MachineTypes).AsNoTracking().ToListAsync());
}

在索引中,我将这个列表显示在一张桌子上:

@model IEnumerable<Application.Models.Machine>

@{
    ViewData["Title"] = "Index";
}

<h2>Index</h2>

<p>
    <a asp-action="Create">Create New</a>
</p>
<form asp-action="Index" method="get">
    <div class="form-actions no-color">
        <p>
            Search by name: <input type="text" name="SearchString" value="@ViewData["currentFilter"]" />
            <input type="submit" value="Search" class="btn btn-default" /> |
            <a asp-action="Index">Volver a lista completa</a>
        </p>
    </div>
</form>
<table class="table">
    <thead>
        <tr> 
                <th>
                    <a asp-action="Index" asp-route-sortOrder="@ViewData["NameSortParm"]">@Html.DisplayNameFor(model => model.MchName)</a>
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.MachineTypes.TypeDescription)
                </th>
                <th>
                    <a asp-action="Index" asp-route-sortOrder="@ViewData["DateSortParm"]">@Html.DisplayNameFor(model => model.FechaCompra)</a>
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.CostoMaq)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.PUnit)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.FechaPUnit)
                </th>
        </tr>
    </thead>
    <tbody>
@foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.MchName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.MachineTypes.TypeDescription)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.FechaCompra)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.CostoMaq)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.PUnit)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.FechaPUnit)
            </td>
            <td>
                <a asp-action="Edit" asp-route-id="@item.Id">Edit</a> |
                <a asp-action="Details" asp-route-id="@item.Id">Details</a> |
                <a asp-action="Delete" asp-route-id="@item.Id">Delete</a>
            </td>
        </tr>
}
    </tbody>
</table>

如您所见,我有一个名为“Create”的 asp-action,它打开 Create 视图,用户可以在其中注册新机器。

这是来自机器控制器的 Create() 代码: 注意:Create 是一个 View,还不是 PartialView

public IActionResult Create()
{
    PopulateMachineTypeDropDownList();
    PopulateMachineTypeDropDownListSupplier();
    PopulateMachineTypeDropDownListStore();

    return View();
}

目标:

从 Index.cshtml 内部将 Create 表单作为模式调用(作为局部视图?)

为此,我编辑了 Index.cshtml 并将其转换为:

<a asp-action="Create">Create New</a>

进入这个:

<a data-toggle="modal" data-target="CreateModal">Create New</a>

此外,我在列出我们库存机器的表格末尾插入了模式代码,并尝试将 Create 视图作为 Partial View 调用。 (当然失败了)。模式代码:

<div class="modal fade" id="CreateModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
            </div>
            <div class="modal-body">
                @Html.RenderPartial("Create", Model)
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

我相信这失败的原因有很多,在未定义为局部视图的东西上使用 RenderPartial 就是其中之一,我希望是主要原因。

问题:

我应该按照哪些步骤将 Create 视图转换为 Index.cshtml 中的局部视图并将其呈现为模态表单?

顺便说一下,这是创建视图的代码:

@model Application.Models.Machine

@{
    ViewData["Title"] = "Create";
}

<h2>Create</h2>

<form asp-action="Create">

        <h4>Machine</h4>
        <hr />
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <div class="form-group">
            <label asp-for="TypeID" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <select asp-for="TypeID" class="form-control" asp-items="ViewBag.TypeID">
                    <option value="">-- Seleccione Tipo --</option>
                </select>
                <span asp-validation-for="TypeID" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="SupplierID" class="col-md-2 control-label">    </label>
            <div class="col-md-10">
                <select asp-for="SupplierID" class="form-control" asp-items="ViewBag.SupplierID">
                    <option value="">-- Seleccione Proveedor --</option>
                </select>
                <span asp-validation-for="SupplierID" class="text-danger">    </span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="StoreID" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <select asp-for="StoreID" class="form-control" asp-items="ViewBag.StoreID">
                    <option value="">-- Seleccione Tienda --</option>
                </select>
                <span asp-validation-for="StoreID" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="MchName" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="MchName" class="form-control" />
                <span asp-validation-for="MchName" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="FechaCompra" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="FechaCompra" class="form-control" />
                <span asp-validation-for="FechaCompra" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="CostoMaq" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="CostoMaq" class="form-control" />
                <span asp-validation-for="CostoMaq" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="PUnit" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="PUnit" class="form-control" />
                <span asp-validation-for="PUnit" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <label asp-for="FechaPUnit" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="FechaPUnit" class="form-control" />
                <span asp-validation-for="FechaPUnit" class="text-danger"></span>
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>

</form>

<div>
    <a asp-action="Index">Back to List</a>
</div>

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}

【问题讨论】:

    标签: asp.net-core bootstrap-modal partial-views


    【解决方案1】:

    进展:

    好的,因为我无法将单个模型渲染到索引视图中以供 PartialView("Create") 使用,所以我这样做了:

                @foreach (var defectsVM in Model)
                {
                    Html.RenderPartial("Create", defectsVM);
    
                }
    

    好吧,没有错误,但是当我单击“创建”链接时,它会弹出创建表单(是的),但当然,它会多次执行并将每个寄存器的数据带到机器表中。

    我怎么能只带一个干净的?

    【讨论】:

      【解决方案2】:

      这是我的旧代码,我认为它会对您有所帮助。它和你的不一样,但你会得到
      局部视图:

      @model App.Domain.PostOffice
              <div class="modal fade" id="Addmodal" tabindex="-1" role="dialog" aria-labelledby="edit" aria-hidden="true" data-keyboard="false" data-backdrop="static">
                  <div class="modal-dialog">
                      <div class="modal-content">
                          <div class="modal-header">
                              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                              <h4 class="modal-title">Post Office</h4>
                          </div>
                          <div class="modal-body form-horizontal ">
                              <div class="row">
                                  <div class="col-md-12">
                                      <div class="row" id="rptshow">
                                          <div class="col-sm-12">
                                              <div class="card-box table-responsive">
                                                  <div class="form-group">
                                                      @Html.HiddenFor(x => x.Id)
                                                      @Html.LabelFor(x => x.PoId, new { @class = "col-md-2 control-label" })
                                                      <div class="col-sm-6">
                                                          @Html.TextBoxFor(x => x.PoId, new { @class = "form-control col-md-4", disabled = "disabled" })
                                                      </div>
                                                  </div>
                                                  <div class="form-group">
                                                      @Html.LabelFor(x => x.Name, new { @class = "col-md-2 control-label" })
                                                      <div class="col-sm-6">
                                                          @Html.TextBoxFor(x => x.Name, new { @class = "form-control col-md-4", required = "required" })
                                                      </div>
                                                  </div>
                                                  <div class="form-group">
                                                      @Html.LabelFor(x => x.Address, new { @class = "col-md-2 control-label" })
                                                      <div class="col-sm-6">
                                                          @Html.TextBoxFor(x => x.Address, new { @class = "form-control col-md-4", required = "required", })
                                                      </div>
                                                  </div>
                                                  <div class="form-group">
                                                      @Html.LabelFor(x => x.PostCode, new { @class = "col-md-2 control-label" })
                                                      <div class="col-sm-6">
                                                          @Html.TextBoxFor(x => x.PostCode, new { @class = "form-control col-md-4", required = "required", data_parsley_minlength = "4", type = "number", palceholder = "" })
                                                      </div>
                                                  </div>
                                                  <div class="form-group">
                                                      @Html.LabelFor(x => x.Hpo, new { @class = "col-md-2 control-label" })
                                                      <div class="col-sm-6">
                                                          @Html.TextBoxFor(x => x.Hpo, new { @class = "form-control col-md-4", required = "required", data_parsley_Maxlength = "2", data_parsley_minlength = "2", type = "number", palceholder = "" })
                                                      </div>
                                                  </div>
                                                  <div class="form-group">
                                                      @Html.LabelFor(x => x.Gpo, new { @class = "col-md-2 control-label" })
                                                      <div class="col-sm-6">
                                                          @Html.TextBoxFor(x => x.Gpo, new { @class = "form-control col-md-4", required = "required", data_parsley_Maxlength = "2", data_parsley_minlength = "2", type = "number", palceholder = "" })
                                                      </div>
                                                  </div>
                                              </div>
                                          </div>
                                      </div>
                                  </div>
                                  <div class="col-md-1"></div>
                              </div>
      
                          </div>
      
                          <div class="modal-footer">
                              <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
                              <button type="submit" class="btn btn-info waves-effect waves-light" id="add">Save changes</button>
                          </div>
      
                      </div>
                  </div>
      
              </div>  
      

      @model App.Domain.PostOffice

      <div class="modal fade" id="Addmodal" tabindex="-1" role="dialog" aria-labelledby="edit" aria-hidden="true" data-keyboard="false" data-backdrop="static">
                  <div class="modal-dialog">
                      <div class="modal-content">
                          <div class="modal-header">
                              <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                              <h4 class="modal-title">Post Office</h4>
                          </div>
                          <div class="modal-body form-horizontal ">
                              <div class="row">
                                  <div class="col-md-12">
                                      <div class="row" id="rptshow">
                                          <div class="col-sm-12">
                                              <div class="card-box table-responsive">
                                                  <div class="form-group">
                                                      @Html.HiddenFor(x => x.Id)
                                                      @Html.LabelFor(x => x.PoId, new { @class = "col-md-2 control-label" })
                                                      <div class="col-sm-6">
                                                          @Html.TextBoxFor(x => x.PoId, new { @class = "form-control col-md-4", disabled = "disabled" })
                                                      </div>
                                                  </div>
                                                  <div class="form-group">
                                                      @Html.LabelFor(x => x.Name, new { @class = "col-md-2 control-label" })
                                                      <div class="col-sm-6">
                                                          @Html.TextBoxFor(x => x.Name, new { @class = "form-control col-md-4", required = "required" })
                                                      </div>
                                                  </div>
                                                  <div class="form-group">
                                                      @Html.LabelFor(x => x.Address, new { @class = "col-md-2 control-label" })
                                                      <div class="col-sm-6">
                                                          @Html.TextBoxFor(x => x.Address, new { @class = "form-control col-md-4", required = "required", })
                                                      </div>
                                                  </div>
                                                  <div class="form-group">
                                                      @Html.LabelFor(x => x.PostCode, new { @class = "col-md-2 control-label" })
                                                      <div class="col-sm-6">
                                                          @Html.TextBoxFor(x => x.PostCode, new { @class = "form-control col-md-4", required = "required", data_parsley_minlength = "4", type = "number", palceholder = "" })
                                                      </div>
                                                  </div>
                                                  <div class="form-group">
                                                      @Html.LabelFor(x => x.Hpo, new { @class = "col-md-2 control-label" })
                                                      <div class="col-sm-6">
                                                          @Html.TextBoxFor(x => x.Hpo, new { @class = "form-control col-md-4", required = "required", data_parsley_Maxlength = "2", data_parsley_minlength = "2", type = "number", palceholder = "" })
                                                      </div>
                                                  </div>
                                                  <div class="form-group">
                                                      @Html.LabelFor(x => x.Gpo, new { @class = "col-md-2 control-label" })
                                                      <div class="col-sm-6">
                                                          @Html.TextBoxFor(x => x.Gpo, new { @class = "form-control col-md-4", required = "required", data_parsley_Maxlength = "2", data_parsley_minlength = "2", type = "number", palceholder = "" })
                                                      </div>
                                                  </div>
                                              </div>
                                          </div>
                                      </div>
                                  </div>
                                  <div class="col-md-1"></div>
                              </div>
      
                          </div>
      
                          <div class="modal-footer">
                              <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
                              <button type="submit" class="btn btn-info waves-effect waves-light" id="add">Save changes</button>
                          </div>
      
                      </div>
                  </div>
      
              </div>  
      

      主视图:

      @{
              ViewBag.Title = "Create";
              Layout = "~/Views/Shared/_Layout.cshtml";
              List<App.Domain.PostOffice> items = ViewBag.Items;
          }
      
          <link href="~/App_Themes/Theme1/plugins/datatables/jquery.dataTables.min.css" rel="stylesheet" type="text/css" />
          <link href="~/App_Themes/Theme1/assets/css/pages.css" rel="stylesheet" type="text/css">
          <link href="../App_Themes/Theme1/assets/css/components.css" rel="stylesheet" type="text/css">
          <style type="text/css">
              input[type="text"] {
                  border: 1px solid #00ffff;
                  background-color: white;
              }
      
              input[type="number"] {
                  border: 1px solid #00ffff;
                  background-color: white;
              }
      
              th {
                  color: white;
              }
          </style>
          <div>
              <button id="addModalButton" value="Add" class="btn btn-primary">Add</button>
          </div>
          @using (Html.BeginForm())
          {
              <div id="modalDiv">
      
              </div>
      
              <div class="row">
                  <div class="col-md-10">
                      <br /><h4 class="m-t-0 header-title"><b>Existing Post Office List </b></h4><br />
                      <table id="datatable-buttons" class="table table-striped table-bordered">
                          <thead style="background:#4c5667;">
                              <tr>
                                  <th>SL.</th>
                                  <th>PO ID No</th>
                                  <th>PO Name</th>
                                  <th>PO Address</th>
                                  <th>Post Code</th>
                                  <th>HPO</th>
                                  <th>GPO</th>
                                  <th>Create By</th>
                                  <th>Action</th>
                              </tr>
                          </thead>
                          <tbody id="postList">
                              @{
              int i = 0;
              foreach (var item in items)
              {
                  i = i + 1;
                  <tr>
                      <td>@i</td>
                      <td>@item.PoId</td>
                      <td>@item.Name</td>
                      <td>@item.Address</td>
                      <td>@item.PostCode</td>
                      <td>@item.Hpo</td>
                      <td>@item.Gpo</td>
                      <td>@item.EntryUser</td>
                      <td>
                          <a href="#" class="on-default edit-row editSup" data-id="@item.Id" id="edit" value="@item.Id"><i class="fa fa-pencil"></i></a>&nbsp;&nbsp;&nbsp;&nbsp;
                      </td>
      
                  </tr>
              }
                              }
      
                          </tbody>
                      </table>
                      <br />
                  </div>
                  <div class="col-md-1"></div>
              </div>
          }
      

      控制器:

      public ActionResult CreatePostOffice()
              {
                  ViewBag.Items = _postOfficeService.All().ToList();
                  return View();
              }
      
              public ActionResult CreatePosto(PostOffice aPostOffice)
              {
                  if(ModelState.IsValid)
                  {
                      var lastPo = _postOfficeService.All().ToList().FirstOrDefault(x => x.PoId == aPostOffice.PoId.Trim());
                      if(lastPo!=null)
                      {
                          aPostOffice.PoId = (Convert.ToInt32(lastPo.PoId) + 1).ToString().PadLeft(4,'0');
                      }
      
                      aPostOffice.EntryUser = User.Identity.Name;
                      aPostOffice.EntryDate = DateTime.Now;
                      _postOfficeService.Add(aPostOffice);
                      _postOfficeService.Save();
                  }
      
                  return RedirectToAction("CreatePostOffice");
              }
      

      【讨论】:

      • 你好。感谢您的回答。我将数据从我的控制器传递到索引视图,如下所示: return View(await _context.Machines.Include(t => t.MachineTypes).AsNoTracking().ToListAsync());所以,我想我应该像这样使用 RenderPartial:@Html.RenderPartial("Create", Models.Machines) 但我得到:'Models' 在实际上下文中不存在。
      • 你到底想传递什么机器列表......如果是这样你已经在@model IEnumerable 中声明了......所以你只需要写...... .. 只有@Html.RenderPartial("Create", Model) ...不是@Html.RenderPartial("Create", Models.Machines)
      • 收到此消息参数 1:无法从 'void' 转换为 'object' + @Html.RenderPartial("Create", Model) :(
      • 也试过这个:@{Html.RenderPartial("Create", Model);} 并得到相同的初始错误:“InvalidOperationException: 传递给 ViewDataDictionary 的模型项的类型为'System.Collections。 Generic.List`1[Application.Models.Machine]',但这个 ViewDataDictionary 实例需要一个“Application.Models.Machine”类型的模型项。”
      • 我明白了...如果您知道需要通过哪个模型...然后编写@Html.RenderPartial("Create", Model[0]) 假设我想通过0索引模型跨度>
      猜你喜欢
      • 2015-03-19
      • 2020-07-15
      • 2017-11-26
      • 1970-01-01
      • 2017-04-27
      • 1970-01-01
      • 2017-05-04
      • 2010-09-07
      相关资源
      最近更新 更多