开发者

Problem accessing ViewData in HTML for MVC3 Razor project

javascript I am passing the value "3" from a Controller into a ViewData variable to be displayed via the HTML.

I have verified that right before the ActionResult is returned, that the value "3" is in the variable (see below code):

public ActionResult Index()
.
.
.
ViewData["ErrCode"] = "3";
                    return RedirectToAction("Index", "Home");

However, the string, when rendered, is always rendered as an empty string (see below):

        $().customAlert();
$(document).ready(function () {
'' = "3";
var strErrCode = '';
alert('Hello!');
});

The above rendered code is from the following code in the tag of the _Layout.cshtml Shared View file. Note that I am even forcing the value "3" into the "ErrCode" variable and the script gets rendered as above.

    $().customAlert();
    $(document).ready(function () {
             '@ViewData["ErrCode"]' = "3";
        var strErrCode = '@ViewData["ErrCode"]';
        alert('Hello!');
    });

I must be using the ViewDa开发者_StackOverflowta incorrectly in the js. How can I accomplish this simple feat?


You are calling RedirectToAction. This has the effect of returning a 302 http status code pointing you at the URL of the Home action on the Index controller.

At that point, you lose whatever was in ViewData. You need to pass the value as part of the URL, for example via the query string:

return RedirectToAction("Index", "Home", new { ErrCode = 3 });

Update: You can also use TempData instead of ViewData. This is a collection that persists data until the next request (and the next request only).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜