-1

I want to assign EST_ID from index.cshtml to Create.cshtml view which uses Html.Editorfor(model=>model.EST_ID).

how to assign EST_ID to Html.Editorfor(model=>model.EST_ID) using TempData or ViewBag by getting EST_ID from table in index.cshtml?

Here's my controller code

public ActionResult Publication(int id)
{
    if (ModelState.IsValid)
    {
        string est = db.EstimateHeaders.Find(id).ToString();
        ViewBag.EST_ID=est;
        return RedirectToAction("Create", "EP");
    }
    return View();
}

Here's Create.cshtml code

@Html.EditorFor(model=>model.EST_ID,
    htmlAttributes : new { @placeholder="EST_ID",
                           @class = "form-control",
                           @readonly = "readonly",
                           @required = "required" } )

How to assign EST_ID value from index.cshtml to create.cshtml EditorFor?

Jasen
  • 14,030
  • 3
  • 51
  • 68

1 Answers1

0

There are a couple of problems with your example.

First, EditorFor needs a non-dynamic expression so you can't use ViewBag or ViewModel directly. Assign the value to a variable if you don't want to use proper View Models.

@{
    var id = ViewBag.EST_ID;
}

@Html.EditorFor(m => id)

Next, you cannot to pass the value through ViewBag to a different action. You don't show your Create action and unless you explicitly assign ViewBag.EST_ID again, the value will be null.

public ActionResult Create()
{
    ViewBag.EST_ID = est;
    return View();
}

To pass a vaule from Publication to Create through redirection, you'll need to use query string parameters or use TempData.

public ActionResult Publication(int id)
{
    string est = ...;
    // TempData.EST_ID = est;   // pass with TempData

    // or use routeValues passed as query string params
    return RedirectToAction("Create", "EP", routeValues: new { est = est });
}

public ActionResult Create(string est)
{
    ViewBag.EST_ID = est;
    // or if set previously
    //   ViewBag.EST_ID = TempData.EST_ID;
    return View();
}
Jasen
  • 14,030
  • 3
  • 51
  • 68
  • i followed your answer, but i am getting `System.Data.Entity.DynamicProxies....` as value in view – Karan Valecha Aug 21 '16 at 05:21
  • i changed `string est = db.EstimateHeaders.Find(id).ToString();` to `string est = db.EstimateHeaders.Find(id).EST_ID.ToString();` everything works flawless. Thankyou!!! – Karan Valecha Aug 21 '16 at 06:01