我的 ViewModel 导致了多个错误

My ViewModel is causing multiple errors

我正在尝试创建一个视图模型,以便我可以在一个页面上显示从多个模型收集的信息,但是我 运行 遇到了多个错误(如下所示)所使用的模型是我的解决方案中的另一个项目。任何帮助将不胜感激。除了显示信息外,我还尝试在创建用户时创建下拉菜单,他们可以 select 每个用户使用的设备。

User.cs(型号

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
using System.Collections.Generic;

namespace FaceToFace.Model
{
    public class User
    {
        public int UserID { get; set; }
        public string CodeName { get; set; }
        public bool UseBriefInstructions { get; set; }
        public ICollection<RegimeItem> RegimeItems { get; set; }
        public Device Device { get; set; }
        public virtual ICollection<Grading> UserGradings { get; set; }

        public User()
        {
            this.RegimeItems = new List<RegimeItem>();
            Device = new Device();
        }


    }

Device.cs(型号)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FaceToFace.Model
{
    public class Device
    {
        public int DeviceID { get; set; }
        public string Name { get; set; }
    }
}

UserDeviceViewModel.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.WebPages.Html;
using FaceToFace.Model;

namespace FaceToFaceWebsite.Models
{
    public class UserDeviceViewModel
    {
        public UserDeviceViewModel()
        {
            User = new User();
            Users = new List<User>();
            Devices = new List<SelectListItem>();
        }

        public User UseBriefInstructions { get; set; }
        public Device Device { get; set; }
        public User User { get; set; }
        public User CodeName { get; set; }
        public IList<SelectListItem> Devices { get; set; }
        public IList<User> Users { get; set; }
    }
}

Views/Patient/Create.cshtml

    @model FaceToFace.Model.User

    @{
        ViewBag.Title = "Create";
    }

    <h2>Create</h2>

    @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true)

        <fieldset>
            <legend>User</legend>

            <div class="editor-label">
                @Html.LabelFor(model => model.CodeName)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.CodeName)
                @Html.ValidationMessageFor(model => model.CodeName)
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.Device.Name, "Device")
            </div>
            <div class="editor-field">
                @Html.DropDownListFor(model => model.User.Device.DeviceID, Model.Devices)
        <input type="submit" value="Save" />
            </div>

            <div class="editor-label">
                @Html.LabelFor(model => model.UseBriefInstructions)
            </div>
            <div class="editor-field">
                @Html.EditorFor(model => model.UseBriefInstructions)
                @Html.ValidationMessageFor(model => model.UseBriefInstructions)
            </div>

            <p>
                <input type="submit" value="Create" />
            </p>
        </fieldset>
    }

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

PatientController.cs

 using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using FaceToFace.Model;
using System.ComponentModel.DataAnnotations;
using FaceToFaceWebsite.Models;

namespace FaceToFaceWebsite.Controllers
{
    public class PatientController : Controller
    {
        private F2FData db = new F2FData();

        //
        // GET: /Patient/
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Index(UserDeviceViewModel viewModelDevice)
        {

            var viewModel = new UserDeviceViewModel();

            viewModel.Devices.Add(new SelectListItem() { Text = "MAU110-10", Value = "1" });
            viewModel.Devices.Add(new SelectListItem() { Text = "MAU110-100", Value = "2" });
            viewModel.Devices.Add(new SelectListItem() { Text = "MAU110-101", Value = "3" });
            viewModel.Devices.Add(new SelectListItem() { Text = "MAU110-102", Value = "4" });
            viewModel.Devices.Add(new SelectListItem() { Text = "MAU110-103", Value = "5" });

            viewModel.Users.AddRange(db.Users.ToList());

            return View(viewModel);
        }

        // GET: /Patient/Details/5

        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
        }

        public ActionResult Create()
        {
            // was ViewBag.DeviceID = new SelectList(db.Devices, "DeviceID", "Name");
            ViewBag.DeviceID = new SelectList(db.Devices, "DeviceID", "Name");
            return View();
        }

        //
        // POST: /Patient/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "UserID,CodeName,UseBriefInstructions")] User user, Device device)
        {
            if (ModelState.IsValid)
            {
                //db.Devices = user.Device.DeviceID;
                db.Users.Add(user);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.DeviceID = new SelectList(db.Devices, "DeviceID", "Name", user.Device.DeviceID);
            return View(user);
        }

        //
        // GET: /Patient/Edit/5

        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            //removed   user.Device.DeviceID
            ViewBag.DeviceID = new SelectList(db.Devices, "DeviceID", "Name");
            return View(user);
        }

        //
        // POST: /Patient/Edit/5

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "UserID,CodeName,UseBriefInstructions")] User user)
        {
            if (ModelState.IsValid)
            {
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.DeviceID = new SelectList(db.Devices, "DeviceID", "Name", user.Device.DeviceID);
            return View(user);
        }

        //
        // GET: /Patient/Delete/5

        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            return View(user);
            //User user = db.Users.Find(id);
            //if (user == null)
            //{
            //    return HttpNotFound();
            //}
            //return View(user);
        }

        //
        // POST: /Patient/Delete/5

        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            User user = db.Users.Find(id);
            db.Users.Remove(user);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}

我将省略编辑视图以避免进一步的垃圾邮件,它基本上包含类似的创建功能,但是我现在遇到多个错误。我已经修复了一些我相信。对于下拉菜单(创建),我收到此错误:

'System.Web.Mvc.HtmlHelper' 不包含 'DropDownListFor' 的定义并且最佳扩展方法重载 'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>, System.Collections.Generic.IEnumerable)' 有一些无效参数

对于患者控制器中的viewModel.Devices.Add,我得到:

'System.Collections.Generic.ICollection.Add(System.Web.WebPages.Html.SelectListItem)' 的最佳重载方法匹配有一些无效参数

连同:

参数 1:无法从 'System.Web.Mvc.SelectListItem' 转换为 'System.Web.WebPages.Html.SelectListItem'

最后在下方我收到来自 AddRange (PatientController) 的错误消息:

'System.Collections.Generic.IList' 不包含 'AddRange' 的定义,并且找不到接受类型 'System.Collections.Generic.IList' 的第一个参数的扩展方法 'AddRange'(您是否缺少 using 指令或程序集引用?)

* **更新 ***

改为PatientController.cs

public ActionResult Index(UserDeviceViewModel viewModelDevice)
        {
            var viewModel = new UserDeviceViewModel(); 

            List<UserDeviceViewModel> viewModelList = new List<UserDeviceViewModel>();
            viewModelDevice.Users.AddRange(db.Users.ToList());
            return View(viewModelList);
        }

UserDeviceViewModel.cs

namespace FaceToFaceWebsite.Models
{
    public class UserDeviceViewModel
    {
        public UserDeviceViewModel()
        {
            Device = new Device();
            User = new User();
            Users = new List<User>();
            Devices = new List<SelectListItem>();
        }

        public Device Device { get; set; }
        public Device Name { get; set; }
        public Device DeviceID { get; set; }

        public User UseBriefInstructions { get; set; }
        public User User { get; set; }
        public User UserID { get; set; }
        public User CodeName { get; set; }

        public List<SelectListItem> Devices { get; set; }
        public List<User> Users { get; set; }
    }
}

Index.cshtml(查看)

@model IEnumerable<FaceToFaceWebsite.Models.UserDeviceViewModel>
@*@model IEnumerable<FaceToFace.Model.User>*@

    @{
        ViewBag.Title = "Index";
    }

    <h2>Your Patients</h2>

    @*Showing @Model.Count() users*@

    <p>
        @Html.ActionLink("Add New User", "Create")
    </p>

    <table>
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.UserID)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.CodeName)
            </th>
            <th>
                @*@Html.DisplayNameFor(model => model.Device.Name)*@Device
            </th>
            <th>
                @Html.DisplayNameFor(model => model.Device.DeviceID)
            </th>

        </tr>

        @foreach (var item in Model)
        {
            <tr>
                <td>
                    @Html.DisplayFor(modelItem => item.UserID)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.CodeName)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Device.Name)
                </td>
                <td>
                    @Html.DisplayFor(modelItem => item.Device.DeviceID)
                </td>
                <td>
                    @Html.ActionLink("Edit", "Edit", new { id = item.UserID }) |
                    @Html.ActionLink("Details", "Details", new { id = item.UserID }) |
                    @Html.ActionLink("Delete", "Delete", new { id = item.UserID })
                </td>
            </tr>
        }

    </table>

我已经把它送到 运行 没有错误,但是我原来的问题是没有来自数据库的数据显示在索引视图上。当我创建一个新用户时它也没有显示。

对于 DropDownList(您已经声明了 User 模型):

@model FaceToFace.Model.User
....
 @Html.DropDownListFor(model => model.Device.DeviceID, (IEnumerable<SelectListItem>)ViewBag.DeviceID)

System.Web.Mvc.HtmlHelper' does not contain a definition for 'DropDownListFor' and the best extension method overload
'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions.Expression>, System.Collections.Generic.IEnumerable)' has some invalid arguments

对于上述错误,DeviceID 是一个整数,它需要是一个字符串,Devices 需要是一个 IEnumerable:

@Html.DropDownListFor(model => model.User.Device.DeviceID, Model.Devices)

所以把publicIList<SelectListItem> Devices { get; set; }改成public IEnumerable<SelectListItem> Devices { get; set; }

The best overloaded method match for 'System.Collections.Generic.ICollection.Add(System.Web.WebPages.Html.SelectListItem)' has some invalid arguments The best overloaded method match for 'System.Collections.Generic.ICollection.Add(System.Web.WebPages.Html.SelectListItem)' has some invalid arguments

以上两个错误在引用之间存在某种不匹配,您的控制器有 using System.Web.Mvc 视图以某种方式拾取 System.Web.WebPages.Html,检查是否没有 @using System.Web.WebPages.Html 在视图中。

System.Collections.Generic.IList' does not contain a definition for 'AddRange' and no extension method 'AddRange' accepting a first argument of type 'System.Collections.Generic.IList' could be found (are you missing a using directive or an assembly reference?)

将您的 Users 属性 改为 IEnumerable

public IEnumerable<User> Users { get; set; }