在局部视图中使用不同的模型

use different model in the partial view

我有一个使用 ClassA 作为模型的视图 view1.cshtml,在 view1 中有一个局部视图。我希望​​局部视图使用 ClassB 作为模特。

这可能吗?

编辑 添加classB

public class Device
    {

        public int DeviceId { get; set; }

        public string SerialNo { get; set; }

        public string IMME { get; set; }

        public string RefNo { get; set; }

        public string Supplier { get; set; }

        public string Brand { get; set; }

        public string ModelNo { get; set; }

        public DateTime PurchaseDate { get; set; }

        public DateTime RegisterDate { get; set; }

        public string Notes { get; set; }

        public virtual ICollection<ContractsDevice> ContractsDevices { get; set; }
    }

这里是 Action 方法:

[HttpGet]
        public ActionResult AssignDevice()
        {
            //list of devices
            List<Device> dev = new List<Device>();
            dev.Add(new Device { Brand = "Samsung" });
            dev.Add(new Device { Brand = "SONY" });

            return PartialView();
        }

这里是局部视图:

<div class="modal-header">
    <h4 class="modal-title">Assign Device</h4>
</div>
<div class="modal-body">
    Devices list here
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-primary">Save</button>
    <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>

首先,您实际需要的视图是 List<Device> 而不仅仅是 Device,因此您的视图应该是这样的:

@model System.Collections.Generic.List<Device>

<div class="modal-header">
    <h4 class="modal-title">Assign Device</h4>
</div>
<div class="modal-body">
    @foreach(var device in Model)
    {
        <div>@device.SerialNo</div>
    }
</div>
<div class="modal-footer">
    <button type="button" class="btn btn-primary">Save</button>
    <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>
</div>

其次,您实际上将此称为子操作,而不仅仅是部分操作。所以你应该像这样从父视图中调用它:

@Html.Action("AssignDevice")

最后,不要忘记return您在操作中的数据:

return PartialView(dev);