MVC控制器在更新Div内容之前返回内容

本文关键字:返回 Div 控制器 更新 MVC | 更新日期: 2023-09-27 17:55:02

我使用ajax与MVC。

如何更新div内容return RedirectToAction("action","controller")

但是之前的调用像返回Content("Successfully update")消息与javascript或没有javascript?

等控制器:

 if(Success)
    {
         return Content("Successfully updated");
    }
    else
    {
         return Content("Error");
    }
剃刀:

<div id="result"> 

    <form action="/controller/action" data-ajax-update="#result" 
    data-ajax="true" data-ajax-method="POST" data-ajax-mode="replace" method="post ">
<!-- Inputs was here -->
    </form>
    <div id="Content ">
<!-- DataList (partial content) was here -->    
    </div>

MVC控制器在更新Div内容之前返回内容

你可以使用AjaxOptions:

@using (Ajax.BeginForm("action", "controller", new AjaxOptions 
                        { UpdateTargetId = "Content",
                          OnFailure = "OnFailure",
                          OnSuccess = "OnSuccess"}))
{
...
}

<script type="text/javascript">
    function OnSuccess(data) {
         $("#Content").html("Successfully updated");
    }
    function OnFailure(request, error) {
        alert("Error!");
    }
</script>

控制器应该检查:

if(Success)
    {
         return Content("Successfully updated");
    }
    else
    {
         return Json(new { success = false, message = "Error!"});
    }
然后在JS的OnSuccess函数中:
function OnSuccess(data) {
        if (data.success === false){
             alert(data.message);
             $("#Content").html(data.message);
        }
        else
             $("#Content").html(data);
}