Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

c# - Why isn't viewbag value passing back to the view?

straight forward question , can't seem to get my viewBag value to display in a view that the user is directed to after completing a form.

Please advise..thanks

My Index ActionResult simple returns model data..

public ActionResult Index()
{
    var source = _repository.GetByUserID(_applicationUser.ID);
    var model = new RefModel
    {
        test1 = source.test1,
    };
    return View(model);
}

My Get Edit" ActionResult , simply uses the same model data as Index.

My Post "Edit" ActionResult, assigns the new values if any to the model and redirects to the Index page, but Index page does not display ViewBag value ??

[HttpPost]
public ActionResult Edit(RefModell model)
{
    if (ModelState.IsValid)
    {
        var source = _repository.GetByUserID(_applicationUser.ID);
        if (source == null) return View(model);

        source.test1 = model.test1;
        _uow.SaveChanges();

        @ViewBag.Message = "Profile Updated Successfully";
        return RedirectToAction("Index");      
    }
    return View(model);
}

And in my Index view...

@if(@ViewBag.Message != null)
{
    <div>
        <button type="button">@ViewBag.Message</button>
    </div>
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

ViewBag only lives for the current request. In your case you are redirecting, so everything you might have stored in the ViewBag will die along wit the current request. Use ViewBag, only if you render a view, not if you intend to redirect.

Use TempData instead:

TempData["Message"] = "Profile Updated Successfully";
return RedirectToAction("Index");

and then in your view:

@if (TempData["Message"] != null)
{
    <div>
        <button type="button">@TempData["Message"]</button>
    </div>
}

Behind the scenes, TempData will use Session but it will automatically evict the record once you read from it. So it's basically used for short-living, one-redirect persistence storage.

Alternatively you could pass it as query string parameter if you don't want to rely on sessions (which is probably what I would do).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...