Search code examples
c#asp.net-mvcasp.net-mvc-4editorformodel

Unable to display data using EditorFoModel html helper in MVC


I want to display names of mobiles beside checkboxes. Hence I have used the below code with EditorForModel but what it renders in just 12 . I don't understand why it displays 12 instead of names of mobiles.

I have used Ado.net entity model for generating the model class from the database table Mobile.so I have a model class named Mobile.cs as

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

    public partial class Mobile
    {
        public int Model { get; set; }
        public string Type { get; set; }
        public string Cost { get; set; }
        public Nullable<bool> IsSelected { get; set; }
    }
}

And in HomeController, I have a action method as

public ActionResult checkboxfun()
        {
            GadgetsContext gc = new GadgetsContext();
            return View(gc.Mobiles);
        }

Now I have used the Editor Template by naming the view as Mobile as below.

@model MvcDropdown.Models.Mobile

@Html.HiddenFor(m=>m.Model)
@Html.HiddenFor(m=>m.Type)

@Html.EditorFor(m=>m.IsSelected)
@Html.DisplayFor(m=>m.Type)

And i the checkboxfun view I have the following code.

@model IEnumerable<MvcDropdown.Models.Mobile>

@using(Html.BeginForm())
{
@Html.EditorForModel()     
    <br />
    <input type="submit" value="submit" />
}

Now I'm unable to view the data from the database.


Solution

  • Your generating 1 2 because the method is not finding a matching template, and will default to rendering the vale of the first property of the model (in your case you have 2 items in the collection with Model = 1 and Model = 2.

    Your template must be named Mobile.cshtml to match the class name, and be located in either the /Views/Shared/EditorTemplates or /Views/yourControllerName/EditorTemplates (in your case /Views/Home/EditorTemplates) folder