开发者

MVC3 Partial View - Is it better Ajax.BeginForm or Ajax.ActionLink?

开发者 https://www.devze.com 2023-02-20 11:15 出处:网络
I have a Partial View with two opposite ActionLinks inside: <div id=\"divStatus> @if (IsAuthenticated)

I have a Partial View with two opposite ActionLinks inside:

    <div id="divStatus>  
    @if (IsAuthenticated) 
        Html.ActionLink("Say Bye", "ProcBye", "Account")
    else 
        Html.ActionLink("Say Hi", "ProcHi", "Account")
    </div>

Each Action link calls a different method on the Controller.

I hear I should use Ajax.BeginForm but I'm still NOT clear how to put this? My understanding is that I need a <div id="divStatus"> to display the result, but in my case ...the result is the Partial View itself.

QUESTION: How do I ensure make it so the Controller just refreshes the calling Partial View??

Shall I just add a div outside the PV?

Shall I add the div inside the PV surrounding the '@if (IsAuthenticate)' call?

Is it better to use Ajax.BeginForm or Ajax.ActionLink in this case?

CODE: What should the code for the Controller look like开发者_如何学编程?

    public ActionResult ProcBye()
    {
        // do something on the server
        // set IsAuthenticated = false;

        return PartialView("_myPV");
    }

There is NO Validation Involved, NO "external" div that needs to be populated, just a simple refresh of the PV independently from what page the PV is located.

Any help will be truly appreciated !!!


Personally I wouldn't use neither. I would use a separate javascript file in which I would AJAXify the link:

$(function() {
    $('.mylink').click(function() {
        $('#resultdiv').load(this.href);
        return false;
    });
});

where resultdiv will be a div which will be update with the partial result returned from the controller action:

<div id="resultdiv"></div>

You just need to put the mylink class:

@if (IsAuthenticated) 
{
    @Html.ActionLink("Say Bye", "ProcBye", "Account", null, new { @class = "mylink" })
}
else 
{
    @Html.ActionLink("Say Hi", "ProcHi", "Account", null, new { @class = "mylink" })
}

You could also use Ajax.ActionLink if you wanted to:

@if (IsAuthenticated) 
{
    @Ajax.ActionLink("Say Bye", "ProcBye", "Account", new AjaxOptions { UpdateTargetId = "resultdiv" })
}
else 
{
    @Ajax.ActionLink("Say Hi", "ProcHi", "Account", new AjaxOptions { UpdateTargetId = "resultdiv" })
}

Just don't forget to include the jquery unobtrusive ajax script in this case:

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>
0

精彩评论

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