ASP MVC 5 Html.EditorFor not working / Unable to access/use Default Editor Templates

1.4k views Asked by At

While attempting access/use the default editor templates in MVC5.

I receive the error:

The model item passed into the dictionary is of type 'System.String', but this dictionary requires a model item of type 'MvcContrib.UI.InputBuilder.Views.PropertyViewModel`1[System.Object]'.

Why is this happening?

Some background:

My model (TestModel.cs):

namespace MyTest.Web.Controllers.Models
{
    public class TestModel
    {
        public TestModel()
        {
            Name = "Fred";
        }

        public string Name { get; set; }

    }
}

My Controller (MyTestController.cs):

namespace MyTest.Web.Controllers
{
    public class MyTestController : Controller
    {
        [HttpGet]
        public ActionResult Index()
        {
            TestModel testData = new TestModel();
            return View(testData);
        }

        ...

    }
}

My View (Index.cshtml):

@model MyTest.Web.Controllers.Models.TestModel
@{
    ViewBag.Title = "MyTest";
    Layout = "~/Views/Shared/_Layout.cshtml";

}
<div class="mainDisplay">
    <h2>Test</h2>
    <div>
        @using (Html.BeginForm("ProcessResults", "MyTest", FormMethod.Post))
        { 
            <div style="display:block;">
                <div style="display:inline;">Name:</div>
                <div style="display:inline;">@Html.EditorFor(x => x.Name)</div>
            </div>
            <div style="display:block;">
                <input type="submit" name="Submit" value="Submit" />
            </div>
        }
    </div>
</div>

The error occurs on the following line

<div style="display:inline;">@Html.EditorFor(x => x.Name)</div>

and the view will not render

Things I have tried:

  • The sample from "ASP.NET MVC Basics Part 1: View Model binding" and this sample works without a problem.
  • If I add a custom editor template under ~/Views/Shared/EditorTemplates/Name.cshtml and I invoke @Html.EditorFor(x => x.Name, "Name") then the page renders
  • If I change the code to be @Html.TextBoxFor(x => x.Name, "Name") then the page renders

Finally, the solution has System.Web.Mvc assembly (which should contain the default editor templates).

What am I missing?

0

There are 0 answers