Question

I have an issue using ViewBag with Html.EditorFor. I am trying to pass data from a form field named "ID" from view 'Create.chtml' back to controller. I would like to use ViewBag for this. When I tried to do as I did in the View below, it's throwing an error:

Compiler Error Message: CS1973: 'System.Web.Mvc.HtmlHelper' has no applicable method named 'EditorFor' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched. Consider casting the dynamic arguments or calling the extension method without the extension method syntax.

Please let me know where I am doing it wrong.

Controller:

[HttpPost]
        public ActionResult Create(TABLE_CODES dc)
        {
            try
            {
                using (var db = new InpEntities())
                {
                    TABLE_CODES codes = new TABLE_CODES(); //TABLE_CODES has data with various columns  - ID, NAME, DATE, SOURCE etc.
                    ViewBag.keys = codes;
                    
                    db.AddToTABLE_CODES(dc);

                    db.SaveChanges();
                }

                return RedirectToAction("Index");
            catch
            {
                return View();
            }
        }

View: Create.chtml

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>
@using (Html.BeginForm()) {
    @Html.ValidationSummary(true)
    <fieldset>
    
        <div class="editor-label">ID</div>

        <div class="editor-field">
            @Html.EditorFor(ViewBag.keys.ID) @****** THIS IS NOT WORKING ********@
        </div>
        
        <p>
            <input type="submit" value="Create" />
        </p>
    </fieldset>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>
        
        
        
        
        
Was it helpful?

Solution

@Html.EditorFor requires a strongly-typed model. It cannot be used with data from the ViewBag.

If you must use ViewBag to pass data to the view, use @Html.TextFor(...) instead to manually setup the input field.

However, I recommend you use a strongly-typed model.

Edit:

Model:

public class MyModel
{
  public TABLE_CODES Keys { get; set; }
}

Controller:

var model = new MyModel();
model.Keys = new TABLE_CODES();
return View(model);

View:

@model MvcApplication1.MyModel
....

@Html.EditorFor(m => m.Keys)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top