Dusko Murtovski
Dusko Murtovski

Reputation: 158

Prevent reload on Ajax.BeginForm

How can I prevent page reloading when submitting form in partial view? There are a lot of examples but it seems that non of them is working for me. This is what I have. Partial view (Razor) which calls this:

@using (Ajax.BeginForm("SaveReply", "Home", null, new AjaxOptions { HttpMethod = "Post" }, new { target = "_self" }))
{
    <div class="input-group wall-comment-reply" style="width:100%">
        @Html.Hidden("eventid", @item.EventID)
        <input name="txtReply" type="text" class="form-control" placeholder="Type your message here...">
        <span class="input-group-btn">
            <button class="btn btn-primary" id="btn-chat" type="submit">
                <i class="fa fa-reply"></i> Reply
            </button>
        </span>
    </div>
}

Then I have my action method in the controller:

[HttpPost]
public void SaveReply(string txtReply, string eventid)
{
    //some code

}

The controller action is fired but after that it is automatically redirected to localhost/home/SaveReply

Maybe the problem is that this partial view is rendered from string. I took the code from:

How to render a Razor View to a string in ASP.NET MVC 3?

Also amongs other things i tried this:

http://geekswithblogs.net/blachniet/archive/2011/08/03/walkthrough-updating-partial-views-with-unobtrusive-ajax-in-mvc-3.aspx

I would appreciate any help.

Upvotes: 2

Views: 4070

Answers (1)

Dusko Murtovski
Dusko Murtovski

Reputation: 158

I found the problem.

It seems that you need to reference the Unobtrusive scripts. Just install them from NuGet:

Install-Package Microsoft.jQuery.Unobtrusive.Ajax

And then reference it from the View that calls the Partial View:

<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

And miraculosly it works without any other changes. More explanations can be found here:

[Why does Ajax.BeginForm replace my whole page?

and here:

[Why UnobtrusiveJavaScriptEnabled = true disable my ajax to work?

It seems that you need to use it if you are using Ajax.* helpers in MVC 3 and higher.

Upvotes: 7

Related Questions