Gate
Gate

Reputation: 495

MVC - Ajax.BeginForm does not working

I am using Ajax Form to render partial view in the page.
see below code

<script type="text/javascript" src="<%: Url.Content("~/Scripts/jquery-1.7.1.min.js") %>"></script>

<script type="text/javascript" src="<%: Url.Content("~/Scripts/jquery.unobtrusive-ajax.js") %>"></script>
<script type="text/javascript" src="<%: Url.Content("~/Scripts/MicrosoftAjax.js") %>"></script>
<script type="text/javascript" src="<%: Url.Content("~/Scripts/MicrosoftMvcAjax.js") %>"></script>

<form id="aspnetForm" runat="server" style="height: 100%;">
<% using (Ajax.BeginForm("demo", "demo", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "divToUpdate" }, new { @ID = "AjaxForm" }))
                   {  %>

                    <%= Html.DropDownList("Demo", list, new { @id = "id", @class = "dropdown" })%>
                    <% }%>
                    <input type="submit" value="Save" />
                    <div id="divToUpdate">
                        <% Html.RenderPartial("UserControls/DemoPage"); %>
                    </div>

                <% }%></form>

In this i include 4 js. I have a page with Form tag and inside that i have a prtial view page. when i am select dropdownlist and click on save button i want ajax post but i found that whole page is reload .

Any Idea about this?

Thanks

Upvotes: 2

Views: 4782

Answers (1)

Harsh Baid
Harsh Baid

Reputation: 7249

Problem is,

  1. You cannot have nested form tags in html

Try as below,

<% using (Ajax.BeginForm("demo", "demo", new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "divToUpdate" }, new { @ID = "AjaxForm" }))
{  %>
    <%= Html.DropDownList("Demo", list, new { @id = "id", @class = "dropdown" })%>
    <input type="submit" value="Save" />
<% }%>
<div id="divToUpdate">
    <% Html.RenderPartial("UserControls/DemoPage"); %>
</div>

You could also change drop down to auto postback, then you would not need separate submit button,

<%= Html.DropDownList("Demo", list, new { @id = "id", @class = "dropdown", @onchange = "$(this).closest('form').submit();" })%>

Upvotes: 5

Related Questions