【问题标题】:How to assign data to EditorFor using TempData or ViewBag如何使用 TempData 或 ViewBag 将数据分配给 EditorFor
【发布时间】:2016-08-20 20:31:42
【问题描述】:

我想将 index.cshtml 中的 EST_ID 分配给使用 Html.Editorfor(model=>model.EST_ID)Create.cshtml 视图。

如何通过从 index.cshtml 中的表中获取 EST_ID 来使用 TempData 或 ViewBag 将 EST_ID 分配给 Html.Editorfor(model=>model.EST_ID)

这是我的控制器代码

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

这里是 Create.cshtml 代码

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

如何将 index.cshtml 中的 EST_ID 值分配给 create.cshtml EditorFor?

【问题讨论】:

    标签: c# asp.net-mvc entity-framework razor viewbag


    【解决方案1】:

    你的例子有几个问题。

    首先,EditorFor 需要一个非动态表达式,因此您不能直接使用 ViewBag 或 ViewModel。如果您不想使用正确的视图模型,请将值分配给变量。

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

    接下来,您不能通过 ViewBag 将值传递给不同的操作。您不会显示您的 Create 操作,除非您再次明确指定 ViewBag.EST_ID,否则该值将为 null。

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

    【讨论】:

    • 我听从了你的回答,但我得到 System.Data.Entity.DynamicProxies.... 的价值
    • 我将string est = db.EstimateHeaders.Find(id).ToString(); 更改为string est = db.EstimateHeaders.Find(id).EST_ID.ToString(); 一切正常。谢谢!!!
    猜你喜欢
    • 1970-01-01
    • 2015-10-12
    • 2014-11-01
    • 2011-12-21
    • 1970-01-01
    • 2016-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多