DForck42
DForck42

Reputation: 20327

Show current value in Html.EditorFor()

I have a view named EditEmployee.shtml that was generated by Visual Studios for me. In it, there's a line that creates the text box to allow an Employee record to be modified.

@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })

Here's the controller:

public ActionResult EditEmployee(int id = 0)
{
    using (MVCTrainingDB db = new MVCTrainingDB())
    {
        var emp = db.Employees.Find(id);

        if (emp == null)
        {
            return RedirectToAction("Index", "Home");
        }
        else
        {
            return View();
        }

    }                        
}

This works perfectly, except that it doesn't show what the current value is for the model, instead it's just blank. How can I modify this to set the value of the textbox to model.Name?

Upvotes: 1

Views: 717

Answers (1)

Shyju
Shyju

Reputation: 218702

You need to pass the object to the view

var emp = db.Employees.Find(id);
if (emp == null)
{
    return RedirectToAction("Index", "Home");
}
else
{
    return View(emp );
}

Upvotes: 3

Related Questions