На частичной странице нет ViewData Asp.NET IEnumerable - PullRequest
0 голосов
/ 19 марта 2019

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

Нет элемента ViewData типа 'IEnumerable', который имеетключ 'QuestionType' в принципе проблема, кажется, в выпадающем html.

Вот мой частичный:

 <div class="form-group">
        @Html.LabelFor(model => model.QuestionType, "QuestionType", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("QuestionType", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.QuestionType, "", new { @class = "text-danger" })
        </div>
    </div>

Мой контроллер вопросов

public ActionResult Create()
    {
        ViewBag.QuestionType = new SelectList(db.QuestionTypes, "Id", "Name");
        return View();
    }

    // POST: MyQuestions/Create
    // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
    // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "Id,Title,Description,QuestionDate,Tags,QuestionType")] MyQuestion myQuestion)
    {
        if (ModelState.IsValid)
        {
            db.MyQuestions.Add(myQuestion);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        ViewBag.QuestionType = new SelectList(db.QuestionTypes, "Id", "Name", myQuestion.QuestionType);
        return View(myQuestion);
    }

И вот как я называю частичное:

<div class="modal-body">
            @Html.Partial("_CreatePartial", new MyWebAppInMVC.Database.MyQuestion())
        </div>

В верхней части частичного я использую следующую строку:

@using (Html.BeginForm("Create", "MyQuestions", FormMethod.Post, new { id = "AddModal" }))

Что не так с моим кодом?

Ответы [ 2 ]

0 голосов
/ 20 марта 2019

Просто напишите ваш @Html.DropDownList следующим образом:

@Html.DropDownList("QuestionType", ViewBag.QuestionType as SelectList,"Select Question Type", htmlAttributes: new { @class = "form-control" })
0 голосов
/ 20 марта 2019

Исключение произошло, потому что QuestionType является свойством ViewBag, и вы не возвращаете какую-либо модель в представление, также содержит потенциальную коллизию именования, поскольку QuestionType уже существует как свойство viewmodel:

ViewBag.QuestionType = new SelectList(db.QuestionTypes, "Id", "Name");
return View();

И вы не указываете списки параметров при использовании DropDownList helper:

@Html.DropDownList("QuestionType", null, htmlAttributes: new { @class = "form-control" })

Рекомендуемый способ предоставления списков параметров в раскрывающемся списке - создание строго типизированного свойства viewmodel для хранения списков параметров, как показано в примере ниже:

public class MyQuestion
{
    // other properties

    // this property bounds to dropdownlist
    public int QuestionType { get; set; }

    // option list property
    public List<SelectListItem> QuestionTypeList { get; set; }
}

После этого измените действие контроллера и частичное представление, чтобы сохранить выбранное значение:

Контроллер

public ActionResult Create()
{
    var myQuestion = new MyQuestion();

    myQuestion.QuestionTypeList = db.QuestionTypes.Select(x => new SelectListItem 
    {
        Text = x.Name, 
        Value = x.Id 
    }).ToList();
    return View(myQuestion);
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(MyQuestion mq)
{
    if (ModelState.IsValid)
    {
        // process data and redirect
    }

    mq.QuestionTypeList = db.QuestionTypes.Select(x => new SelectListItem 
    { 
        Text = x.Name, 
        Value = x.Id, 
        Selected = (x.Id == mq.QuestionType) 
    }).ToList();
    return View(mq);
}

Частичный вид

<div class="form-group">
    @Html.LabelFor(model => model.QuestionType, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.QuestionType, Model.QuestionTypeList, new { @class = "form-control" })
        @Html.ValidationMessageFor(model => model.QuestionType, "", new { @class = "text-danger" })
    </div>
</div>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...