ASP.NET MVC. Specific URL for partial views

2019-07-19 13:01发布

I'm new to ASP.NET MVC. So my question may seem to be little bit naive. Anyway I've spent hours searching for any information on my topic, but no result. So I would be very grateful for your help.

So this is my problem.

In my Index view I have a div, where I put contents of different Partial Views depending on the link that user clicks.

Here's the code. Index.cshtml:

<div id="dynamicContent"></div>

<a href="#" onclick="@String.Format("updateContent('{0}');", Url.Action("DynamicContent", "Agent", new {name = "AboutCbsrAgent"}))">About Cbsr Agent</a>

<a href="#" onclick="@String.Format("updateContent('{0}');", Url.Action("DynamicContent", "Agent", new {name = "ApplicationAreasOfCBSR"}))">Application Areas Of CBSR</a>

JavaScript:

function updateContent(contentUrl) {

    $.ajax({
        url: contentUrl,
        type: "GET",
        success: function (data) {
            $('#dynamicContent').html(data);
        }
    });
}

Controller:

public class AgentController : Controller
{
    //Index action
    public ActionResult DynamicContent(string name)
    {
        return PartialView(String.Format("Partial/" + name));
    }
}

So, everything works fine. When user clicks the link, the appropriate partial view is loading into the div. The problem is that in adrees bar of a browser i get the following URL: example.com/Agent# whatever link i click.

So my question: Is there any way to generate the unique URL for each partial view? For example: example.com/agent/partial/AboutCbsrAgent. And is it possible to make so that when I paste this link into the browser's address bar, the whole view and NECESSARY partial view will be displayed?

Thank you in advance for your help!

2条回答
2楼-- · 2019-07-19 13:10

If you want to avoid the # in your url use:

<a href="javascript:void(0);" onclick="@String.Format("updateContent('{0}');", Url.Action("DynamicContent", "Agent", new {name = "AboutCbsrAgent"}))">About Cbsr Agent</a>

If you know your users are mainly FF, Chrome, IE9 <, or you don't care if the browser doesn't support it, you can use history.pushState

Although you will still have to find a solution for loading the correct content if the user revisists that url (with pushState)

查看更多
乱世女痞
3楼-- · 2019-07-19 13:15

You can create two separate actions in your AgentController, for the two URLs, and pass name of the partial view you want to render. Something like:

public ActionResult AboutCbsrAgent() 
{
    ViewBag.MyPartialView = "AboutCbsrAgent";
    ....

    return View("Index");
}

Then in your Index.cshtml:

<div id="dynamicContent">
    @Html.Partial(ViewBag.MyPartialView)
</div>

You'll probably need to adjust the paths, but you get the idea.

查看更多
登录 后发表回答