«Нет элемента ViewData типа« IEnumerable <SelectListItem>»с ключом« Оборудование ». ' - PullRequest
0 голосов
/ 06 февраля 2020

Я пытаюсь найти решение для этой ошибки, я нашел его, но почти каждое решение, которое я пробовал, и я не знаю, что не так, потому что я все еще получаю эту ошибку.

Я получил две таблицы в одной базе данных : Запрос, ListOfEquipment введите описание изображения здесь

VIEW

@model ITEL.Models.Request

@{
    ViewBag.Title = "AddOrEdit";
    Layout = null;
}
<div class="form-group">
                    @Html.LabelFor(model => model.Equipment, htmlAttributes: new { @class = "control-label col-md-3" })
                    <div class="col-md-6">
                        @Html.DropDownListFor(model => model.Equipment, ViewBag.equipmentList as SelectList, new { @class = "form-control", @onChange = "SelectedValue(this)" })

                        @Html.ValidationMessageFor(model => model.Equipment, "", new { @class = "text-danger" })
                    </div>
                </div>

<div class="form-group">
                    @Html.LabelFor(model => model.Username, htmlAttributes: new { @class = "control-label col-md-3" })
                    <div class="col-md-6">
                        @Html.EditorFor(model => model.Username, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Username, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Department, htmlAttributes: new { @class = "control-label col-md-3" })
                    <div class="col-md-6">
                        @Html.EditorFor(model => model.Department, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Department, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.DateRequest, htmlAttributes: new { @class = "control-label col-md-3" })
                    <div class="col-md-6">
                        @Html.EditorFor(model => model.DateRequest, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.DateRequest, "", new { @class = "text-danger" })
                    </div>
                </div>

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

<script>
    //To get selected value an text of dropdownlist
    function SelectedValue(ddlObject) {
        //Selected value of dropdownlist
        var selectedValue = ddlObject.value;
        //Selected text of dropdownlist
        var selectedText = ddlObject.options[ddlObject.selectedIndex].innerHTML;

        //alert popup with detail of seleceted value and text
        alert(" Selected Value: " + selectedValue + " -- " + "Selected Text: " + selectedText);
    }
</script>  

MODEL Запрос (Основная таблица)

using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.ComponentModel.DataAnnotations.Schema;
    using System.Web;
    using System.Web.Mvc;

    public partial class Request
    {
        public int RequestId { get; set; }
        [Required(ErrorMessage = "This field is required.")]
        [DisplayName("Username")]
        public string Username { get; set; }
        [DisplayName("Department")]
        public string Department { get; set; }
        [DisplayName("Date Request")]
        public string DateRequest { get; set; }
        [DisplayName("User Location")]
        public string UserLocation { get; set; }
        [DisplayName("Phone Extension")]
        public string PhoneExt { get; set; }
        public string Equipment { get; set; }
        ...

МОДЕЛЬ ListOfEquipment

namespace ITEL.Models
{
    using System;
    using System.Collections.Generic;

    public partial class ListOfEquipment
    {
        public int Id { get; set; }
        public string EquipmentName { get; set; }
    }
}

КОНТРОЛЛЕР

public ActionResult AddOrEdit(int id=0)
        {
            Request req = new Request();

            if(id != 0)
            {
                    //DBRModels db = new DBRModels();
                    //req = db.Requests.Where(x => x.RequestId == id).FirstOrDefault<Request>();
                   string constr = ConfigurationManager.ConnectionStrings["DBRModels"].ToString();
                   SqlConnection _con = new SqlConnection(constr);
                   SqlDataAdapter _da = new SqlDataAdapter("Select * From ListOfEquipment", constr);
                   DataTable _dt = new DataTable();
                   _da.Fill(_dt);
                   ViewBag.equipmentList = ToSelectList(_dt, "Id", "EquipmentName");

            }
            return View();

        }

        [HttpPost]
        public ActionResult AddOrEdit(Request req)
        {
            try
            {
                if (req.ImageUpload != null)
                {
                    string fileName = Path.GetFileNameWithoutExtension(req.ImageUpload.FileName);
                    string extension = Path.GetExtension(req.ImageUpload.FileName);
                    fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
                    req.ImagePath = "~/AppFiles/images/" + fileName;
                    req.ImageUpload.SaveAs(Path.Combine(Server.MapPath("~/AppFiles/images/"), fileName));
                }
                using (DBRModels db = new DBRModels())
                {
                    if (req.RequestId == 0) { 
                    db.Requests.Add(req);
                    db.Configuration.ValidateOnSaveEnabled = false;
                    db.SaveChanges();
                    }
                    else
                    {
                        db.Entry(req).State = EntityState.Modified;
                        db.SaveChanges();
                    }
                }
                return Json(new { success = true, html = GlobalClass.RenderRazorViewToString(this, "ViewAll", GetAllRequest()), message = "Submitted Successfully!" }, JsonRequestBehavior.AllowGet);

            }
            catch (Exception ex)
            {

                return Json(new { success = false, message = ex.Message}, JsonRequestBehavior.AllowGet);
            }        
        }

        [NonAction]
        public SelectList ToSelectList(DataTable table, string valueField, string textField)
        {
            List<SelectListItem> list = new List<SelectListItem>();

            foreach (DataRow row in table.Rows)
            {
                list.Add(new SelectListItem()
                {
                    Text = row[textField].ToString(),
                    Value = row[valueField].ToString()
                });
            }

            return new SelectList(list, "Value", "Text");
        }
...