Nilmag
Nilmag

Reputation: 573

My ViewModel is causing multiple errors

I am trying to create a viewmodel so i can display the information gathered from multiple models on one page, however im running into multiple errors ( as shown below) For the models used are a part of a different project in my solution. Any help would be greatly appreciated. Along with displaying the information i am trying to create a dropdown for when a user is created they can select which device each user is using.

User.cs (model)

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 (model)

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);
        }
    }
}

I will leave out edit view to avoid further spam it basically contains similar functionality to create, however I am getting multiple errors now. I have fixed a few I believe. For the dropdown (create) i am getting this error:

'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

For the viewModel.Devices.Add in patient controller i am getting:

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

along with:

Argument 1: cannot convert from 'System.Web.Mvc.SelectListItem' to 'System.Web.WebPages.Html.SelectListItem'

and finally below that i am receiving an error from AddRange (PatientController):

'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?)

* **UPDATE ***

Change to the 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 (view)

@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>

I have got it to run without errors however my original problem of no data from the db is showing on the index view. It also does not show when i create a new user either.

Upvotes: 1

Views: 943

Answers (2)

hutchonoid
hutchonoid

Reputation: 33306

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

For the above error, DeviceID is an int it needs to be a string and Devices needs to be an IEnumerable:

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

So change public IList<SelectListItem> Devices { get; set; } to 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

The two above errors there is some kind of miss-match between references, you controller has the using System.Web.Mvc the view is somehow picking up System.Web.WebPages.Html, check that there is no @using System.Web.WebPages.Html in the view.

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?)

Change your Users property to be an IEnumerable instead:

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

Upvotes: 1

aguetat
aguetat

Reputation: 514

For the DropDownList (you already declare the User model):

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

Upvotes: 2

Related Questions