Search code examples
asp.net-mvcparameter-passingviewbag

Pass URL to new View as a parameter


I've spent a couple of hours trying to work out a way to do this. It's such a simple requirement that I can't believe I need to create view models or anything so grandiose.

Very simply, using MVC5, I have a View, let's call it Page1, on which there is a hyperlink. When the user clicks that hyperlink, I want them to be taken to a new View, Page2. On Page2 is an iframe. I want to set the src attribute of that iframe to the URL of Page1, the View that the user was redirected from.

So, if I could maybe use the ViewBag (which people on here don't seem to recommend), to pass the URL of Page1 from that View to the Controller for Page2, and then use Razor in my markup on Page2 to define the src attribute of the iframe, I imagine that'd work fine. Unfortunately, people don't seem to like using ViewBag, and also, I can't find an end-to-end description of how to actually achieve this in code.

Can somebody give me an appropriately straightforward solution to this problem?


Solution

  • A ViewModel for a View can simply be a string - so if you only need to pass a single value in to the view (the URL to use as the src), then in Page2.cshtml, you just define the model at the top like so:

    @model string

    To use that as the src attribute, you just do e.g.

    <iframe src="@Model" .... >

    And from the controller, you pass the url string as the model to the view like so:

    return View("Page2", myUrlStringVariable);

    So, to recap, a ViewModel doesn't necessarily have to be a new class you create - for the most basic scenarios like this, you can just use e.g. a string as the ViewModel. As soon as you start having multiple bits of data to pass in to a View, that's typically when you'd look to create a specific ViewModel class.