0

I have a very simple dropdown list that's supposed to return a foreign key so that I can associate the uploaded files with a Category.

I am using MVC-5 with Entity Framework. The queries are all actually in a repository so don't flame me for that.

Note: The categories can be seen in the dropdown list. It is when I'm trying to Post the data back that I'm receiving a couple of errors.

First I will show you the two ways I've tried to implement the Dropdownlist then I'll show you my model, view and controller code

First Way

I used the Viewbag to create a SelectList which I then use for the Dropdown menu like so:

Controller:

public class HomeController : Controller
{
    private db Context;

    public HomeController() { db = new Context(); }

    [HttpGet]    
    public ActionResult HelloWorld() 
    {
        var query = db.Table.Where(u => u.Random == "helloworld").ToList();

        ViewBag.DropDown = new SelectList (query, "RandomID", "Random");

        return View();
    }

    [HttpPost]
    public ActionResult HelloWorld(IEnumerable<HttpPostedFileBase> file, Table table) 
    {
        //Do Stuff
    }
}

View:

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

    <input type="file" value="Select Images" multiple />

    @Html.Label("Categories") 
    @Html.DropdownList("DropDown", null, "Select")

    <input type="submit" value="Upload">
}

Error Received: There is no ViewData item of type 'IEnumerable' that has the key 'RandomID'.' (On DropdownList)

The query selected everything in Table that had Random = "helloworld" and made it into a list so by necessity the RandomID should be there

Second Way

I used a model to bind and send the SelectList down and tried to use the model in the Post Action

Controller:

public class HomeController: Controller
{
    private db Context;

    HomeController() { db = new Context(); }

    [HttpGet]
    public ActionResult HelloWorld(Model model)
    {
        dropdown = db.Table.ToList();

        model.List = new SelectList(dropdown, "RandomID", "Random")

        return View(model)
    }

    [HttPost]
    public ActionResult HelloWorld(IEnumerable<HttpPostedFileBase> file, Model model)
    {
        //Do Stuff
    }
}

View:

View is exactly the same as above except for

@Html.DropDownListFor(u => u.RandomID, (SelectList)Model.List, "Select")

and of course

@model Project.Models.Model

Model:

public class Model
{
    public IEnumerable<SelectListItem> List { get; set; }
    public int RandomID { get; set; }
}

Error Received: System.NullReferenceException: Object reference not set to an instance of an object. (On DropdownListFor)

So clearly the ID is empty and is returning null but for the life of me I can't figure why.

My Code

Controller:

public ActionResult EditPhotos(AddImageModel model)
{
    if (Session["id"] == null)
    {
        return RedirectToAction("Index");
    }
    else
    {
        var pics = query.GalleryCategories();
        model.List = new SelectList(pics, "CategoryName", "CategoryName");

        return View(model);
    }
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditPhotos(IEnumerable<HttpPostedFileBase> files, AddImageModel model)
{
    string[] Extensions = new string[] { ".jpg", ".Jpg", ".jpeg", ".png" };

    try
    {
        if (files != null)
        {
            foreach (HttpPostedFileBase file in files)
            {
                var name = Path.GetFileName(file.FileName);
                var ID = model.ID;
                var ext = Path.GetExtension(file.FileName);

                if (Extensions.Contains(ext))
                {
                    var filepath = Path.Combine(Server.MapPath("~/Images/Gallery"), name);

                    query.AddPictures(filepath, ID);

                    file.SaveAs(filepath);

                    return View();
                }
                else
                {
                    ViewBag.Message = "Accepted file types are: '.jpg' '.Jpg' '.jpeg' and '.png'";
                }
            }
        }
    }
    catch (Exception) { return View("Error"); }

    return View();
}

View:

@model DKWebPage.Models.AddImageModel
<div id="modal">
    <div class="form-menu">
        @using (Html.BeginForm("EditPhotos", "Admin", FormMethod.Post, new { @class = "form" }))
        {
            @Html.AntiForgeryToken();

            <input value="Upload Images" type="file" multiple />
            @ViewBag.Message
            @Html.Label("Categories", new { @class = "dd-menu-label" })
            @Html.DropDownListFor(u => u.ID, (SelectList)Model.List, "Select Category", new { @class = "dd-menu" })

            <input type="submit" value="Upload Images" class="smallbutton" style="align-self: flex-end"/>
        }
    </div>
</div>

Model

public class AddImageModel
    {
        public IEnumerable<SelectListItem> List { get; set; }
        public int ID { get; set; }
    }
halfer
  • 19,824
  • 17
  • 99
  • 186
James9oo0
  • 159
  • 12
  • 1
    Because in the POST method you return the view and have not populated `List` as you did in the GET method so its `null` (hence the error) –  Apr 28 '18 at 07:58
  • @StephenMuecke Oh my god – James9oo0 Apr 28 '18 at 08:01
  • 1
    Suggest your read [this question/answer](https://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o) for more detail –  Apr 28 '18 at 08:02
  • 1
    And as a side note, you file input will not send back anything. Not only does it not have a `name` attribute, your `
    ` does not have the `enctype` attribute
    –  Apr 28 '18 at 08:04
  • 1
    You might also want to look at [this answer](https://stackoverflow.com/questions/40199870/how-to-validate-file-type-of-httppostedfilebase-attribute-in-asp-net-mvc-4/40200034#40200034) –  Apr 28 '18 at 08:05
  • @StephenMuecke Thanks alot! Will do, saving lives out here :'D – James9oo0 Apr 28 '18 at 08:08
  • Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. – halfer Apr 29 '18 at 18:15

0 Answers0