Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return View with Model and go to particular anchor tag

Tags:

asp.net-mvc

I have a View with multiple anchors tags. Is there a way to return a View with a model object and go to a particular anchor tag in the view?

For example, my View has anchors like this:

   <a name="Section1"></a>
   ...
   <a name="Section2"></a>

I know I can hit those anchors using:

return Redirect(Url.RouteUrl(new { controller = "myController", action = "myAction" }) + "#Section1");

But I don't think I can use redirect because I need to send a Model:

return View("myAction", model); // how to go to anchor?
like image 238
TTT Avatar asked Apr 09 '13 14:04

TTT


People also ask

How do I return specific view on a controller?

To return a view from the controller action method, we can use View() method by passing respective parameters. return View(“ViewName”) – returns the view name specified in the current view folder (view extension name “. cshtml” is not required. return View("~/Views/Account/Register.

Is it possible to pass a model object to a view from a controller?

The other way of passing the data from Controller to View can be by passing an object of the model class to the View. Erase the code of ViewData and pass the object of model class in return view. Import the binding object of model class at the top of Index View and access the properties by @Model.

What does return View () in MVC do?

The default behavior of the View method ( return View(); ) is to return a view with the same name as the action method from which it's called. For example, the About ActionResult method name of the controller is used to search for a view file named About.

How do I navigate to another view in MVC?

Call the appropriate /controller/action in your respective button click handlers. In your case for the register button handler direct it to /home/register. Have a view for your register functionality. In the register action of your home controller return the view you want to show.


1 Answers

First we need to pass the achor to our view:

Controller:

    ViewBag.Section = "register"; //#register         
    return View();

View:

@if (ViewBag.Section!=null)
{
    <script>
        $(function () {              
                window.location.hash = '#@ViewBag.Section';
        });
    </script>
}

now you can use the "how to scroll to anchor" answer https://stackoverflow.com/a/15906458/7149454

like image 71
Nick Kovalsky Avatar answered Sep 25 '22 18:09

Nick Kovalsky