简体   繁体   中英

Ajax.BeginForm refreshing the whole page in MVC

I've been trying to add some Ajax functionality to my mvc site, however, I run into a problem regarding page refreshing. I've created an rss view on my homepage sidebar, which allows the user to select which rss feed they want to view using a drop down list. Initially I was using the html.begin form option in mvc, however, I decided it would be a cool feature to have the rss feeder refresh, rather than having the whole page refresh. I implemented the ajax.begin form, but the whole page is still refreshing.

Here is the code inside my view:

<div class="rss_feed">
    <h3>RSS Feed</h3>

    @using (Ajax.BeginForm("Index", "Home",
        new AjaxOptions
        {
            HttpMethod = "post",
            UpdateTargetId = "feedList"
        }))
    {
        @Html.DropDownListFor(x => x.SelectedFeedOption, Model.FeedOptions)
        <input type="submit" value="Submit" /> 
    }

    <div id="feedList">
        @foreach (var feed in Model.Articles)
        {
            <div class="feed">
                <h3><a href="@feed.Url">@feed.Title</a></h3>
                <p>@feed.Body</p>
                <p><i>Posted @DateTime.Now.Subtract(@feed.PublishDate).Hours hour ago</i></p>
            </div>   
        }
    </div>
</div>

When the user selects a feed type from the drop down menu, and clicks the submit button, the feed should update to the selected option.

In the _Layout view the following bundle is loaded:

@Scripts.Render("~/bundles/jquery")

Any help would be great.

I use an ajax call in jquery for this

$('#SelectedFeedOption').change(function() {
    $.ajax({
        url: "@(Url.Action("Action", "Controller"))",
        type: "POST",
        cache: false,
        async: true,
        data: { data: $('#SelectedFeedOption').val() },
        success: function (result) {
            $(".feedList").html(result);
        }
   });
});

Then put the contents of your feedList div in a partial view and on your controller

public PartialViewResult FeedList(string data){
    Model model = (get search result);
    return PartialView("_feedList", model);
}

Hopefully this helps.

Did you try initializing the InsertionMode member into the AjaxOptions object initializer?

You also have to include 'jquery.unobtrusive-ajax.js' to make Ajax.BeginForm to work as answered here

 @using (Ajax.BeginForm("Index", "Home", null,
    new AjaxOptions
    {
        HttpMethod = "post",
        InsertionMode = InsertionMode.Replace,            
        UpdateTargetId = "feedList"
    });
{
    @Html.DropDownListFor(x => x.SelectedFeedOption, Model.FeedOptions)
    <input type="submit" value="Submit" /> 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM