Zoners
Zoners

Reputation: 53

How change the content with ajax.BeginForm?

First, sorry for my bad english.

I would like when one people click on the button "Page1", the controller return a renderpartial of the "Page1" and the same things for "page2" and "allPage".

My views is:

@{
ViewBag.Title = "Title";
}
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<h2>Title</h2>

@using (Ajax.BeginForm("NameAction", //controller action name
"NameController", //controller name
new AjaxOptions //ajax options that tell mvc how to perform the replacement
{
UpdateTargetId = "ViewPage", //id of div to update
HttpMethod = "Post" //how to call the controller action
}, new { id = "FormName" }))
{
<input type="submit" id="btn" value="p1" id="p1"/>
<input type="submit" id="btn" value="p2" id="p2"/>
<input type="submit" id="btn" value="AllPage" id="AllPage"/>
<div id="ViewPage">
    //render partial view
</div>        
}

And my controller is:

public class NameController : Controller
{
    [HttpPost]
    public ActionResult NameAction(String btn)
    {
        if (Request.IsAjaxRequest())
        if(btn="p1")
        return PartialView("p1");
        if(btn="2")
        return PartialView("p2");
        if(btn="3")
        return PartialView("p3");


        return View();
    }
}

Request.isAjaxRequest equals always false and the partialview not update the div but erase all page

Thanks for your helps.

Upvotes: 1

Views: 1860

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

Give your submit buttons a name:

<input type="submit" name="btn" value="page1" id="Page1"/>
<input type="submit" name="btn" value="Page2" id="Page2"/>
<input type="submit" name="btn" value="AllPage" id="AllPage"/>

and then:

[HttpPost]
public ActionResult NameAction(string btn)
{
    if (btn == "page1")   
    {
        // the page1 button was clicked
    } 
    else if (btn == "page2")
    {
        // the page2 button was clicked
    }
    else if (btn == "AllPage")
    {
        // the AllPage button was clicked
    }

    ...
}

and if you didn't want to depend on the actual label of the button:

<button type="submit" name="btn" value="p1" id="Page1">Show page 1</button>
<button type="submit" name="btn" value="p2" id="Page2">Show page 2</button>
<button type="submit" name="btn" value="all" id="AllPage">Show all pages</button>

and in the controller you could check against the value.


UPDATE:

Make sure that you have included the jquery.unobtrusive-ajax script to your page so that the Ajax.BeginForm works and sends an AJAX request:

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

Upvotes: 2

Related Questions