0

I have controller method to render PartialView and show SelectList there

Here is method code

public ActionResult AddProject()
    {
        ViewBag.Region = new SelectList(db.Regions, "Id", "Name").ToList();
        return PartialView("/Partials/ProjectModalPartial");
    }

Here is code in PartialView

 <div class="form-group">
    <label for="recipient-name" class="col-form-label">Выберите Город</label>
    @Html.DropDownList("Region", null, "XXXX", htmlAttributes: new { @class = "form-control", @id = "cityId"})
</div>

And here is how I call it in View

<div class="modal-body">
            @Html.Partial("~/Views/Manage/Partials/ProjectModalPartial.cshtml")
        </div>

Here is regions model

public partial class Region
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public Region()
    {
        this.Cities = new HashSet<City>();
    }

    public int Id { get; set; }
    public string Name { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<City> Cities { get; set; }
}

But I have this error

There is no ViewData item of type 'IEnumerable' that has the key 'Region'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: There is no ViewData item of type 'IEnumerable' that has the key 'Region'.

Source Error:

Line 6: Line 7: Выберите Город Line 8: @Html.DropDownList("Region", null, "XXXX", htmlAttributes: new { @class = "form-control", @id = "cityId"}) Line 9: Line 10:

How can I solve it. And why it appears if I have this SelectList in code?

Balance
  • 551
  • 2
  • 10
  • 23
  • Why not go for something like this? @Html.DropDownListFor(x => Model.Id, Model.Cities, htmlAttributes: new { @class = "form-control"}) you might need to fiddle around with the Model.Cities bit, but somethink like this should work. – Lidaranis Mar 20 '18 at 07:14
  • I not using Models in Views@Lidaranis – Balance Mar 20 '18 at 07:15

1 Answers1

1

You need to use this Html.Action overload which will call the action method and the action will return the partial view back. Html.Partial is just rendering the view as html without calling the action so ViewBag.Region is not having the value which is expected :

@Html.Action("AddProject","Project")

assuming the controller class name is ProjectController.

So what will happen now is that Html.Action will call the AddProject action and will return the ActionResult back to your view from which we have called and will render html of partial view ProjectModalPartial.cshtml

Ehsan Sajjad
  • 61,834
  • 16
  • 105
  • 160