Ajax.BeginForm refreshing the whole page in MVC

回眸只為那壹抹淺笑 提交于 2019-12-02 13:48:02

问题


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.


回答1:


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.




回答2:


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" /> 
}


来源:https://stackoverflow.com/questions/16445816/ajax-beginform-refreshing-the-whole-page-in-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!