简体   繁体   中英

Form+Ajax doesn't work properly

Form+Ajax -> Results on exact DIV 3 hours, 53 minutes ago|LINK

Hi,

I need to visualize my partialView (results after a form submission) in a DIV.

I have the following files:

View Man_por.cshtml

...

<div class="col-md4" id="divTabPortfolios">

enter code here@{Html.RenderAction("Load_portfoliosPartial","Management_portfolios");}

<div>

<div class="col-md4" id="divTabPortfolio">

<div>

...

View Load_portfolios_partial

<script src="myscript.js" type="text/javascript"></script>

....

...

@using ( @ Html.BeginForm() )

{

....

...

<button type="submit" class=".." value="Open"/>

}

Script MyScript.js

$(function () {
    $('form').submit(function () {
        if ($(this).valid()) {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    $('#divTabPortfolio').html(result);
                }
            });
        }
        return false;
    });
});

When it shows the result it open entire page and not a partial view (_layout.cshtml+Page) etc.. and it doesn't update the specified DIV.

How could i solve it?

Use @using (Ajax.beginForm()) instead of @using (Html.beginForm() .

MVC supports Ajax forms out-of-the-box.

You then provide the action, controller and selector ( UpdateTargetId is set to the id of the panel to update) like this:

<div id="divTabPortfolio">
    @using (Ajax.BeginForm("SomeAction", "YourController", new { id = optionalParameters }, new AjaxOptions() { HttpMethod = "Post", UpdateTargetId = "divTabPortfolio" }))
    { 
    }
</div>

No need for your own jQuery/Ajax for this sort of basic Ajax post-backs in MVC/Razor.

So long as your action method returns a PartialView you don't need to do anything else.

As suggested, if you could post more of the page it would help provide specifics

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