如何使用TempData或ViewBag给EditorFor分配数据

本文关键字:EditorFor 分配 数据 ViewBag 何使用 TempData | 更新日期: 2023-09-27 18:03:26

我想从索引中分配EST_ID。cshtml to 创建。使用Html.Editorfor(model=>model.EST_ID)的cshtml视图。

如何分配EST_IDHtml.Editorfor(model=>model.EST_ID)使用TempData或ViewBag获得EST_ID表在index.cshtml?

这是我的控制器代码

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();
}

创建。

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

如何从索引中分配EST_ID值。cshtml to create。cshtml EditorFor吗?

如何使用TempData或ViewBag给EditorFor分配数据

你的例子有几个问题。

首先,EditorFor需要一个非动态表达式,所以你不能直接使用ViewBag或ViewModel。如果你不想使用合适的视图模型,就把这个值赋给一个变量。

@{
    var id = ViewBag.EST_ID;
}
@Html.EditorFor(m => id)

接下来,您不能通过ViewBag将值传递给不同的操作。您不显示您的Create操作,除非您再次显式地分配ViewBag.EST_ID,否则该值将为空。

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

通过重定向将值从Publication传递到Create,需要使用查询字符串参数或使用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();
}