2

I have an ASP.NET MVC3 project that uses a tab strip on certain pages. The tab stop is constructed in JavaScript. When the user performs action I would like to be able to redirect them to the correct page with the correct tab open. To achieve this I either need to pass a variable in the URL and get a handle on it using JavaScript or pass a variable back using the ViewBag or TempData and again, get a handle on it using JavaScript.

So my question is, how can I access these variables using JavaScript?

2
  • is your javascript in the cshtml file or in a separate js file? Commented Jan 22, 2012 at 19:09
  • in the cshtml file, why? Commented Jan 22, 2012 at 19:16

1 Answer 1

2

You could pass the value as query string parameter when redirecting and in the target action simply define a view model:

public class MyViewModel
{
    public string MyValue { get; set; }
}

and then have an anchor or a controller action that will redirect to the target action and pass myvalue as query string parameter:

@Html.ActionLink("go to foo", "foo", new { myvalue = "foo bar" })

and when the link is clicked the user gets redirected to the Foo action which takes the view model as argument so that the binding happens automatically and passes this view model to the corresponding view:

public ActionResult Foo(MyViewModel model)
{
    return View(model);
}

and in the corresponding view you could do whatever you want with the view model:

@model MyViewModel
<script type="text/javascript">
    var myValue = @Html.Raw(Json.Encode(Model.MyValue));
    // TODO: do something with the value
</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.