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

时间:2016-07-05 08:01:07

标签: c# asp.net-mvc

我在MVC中使用ajaxform。

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

之前使用javascript或没有javascript调用返回Content("Successfully update")消息?

像 控制器:

 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>

2 个答案:

答案 0 :(得分:1)

您可以使用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>

答案 1 :(得分:0)

Controller应该检查:

if(Success)
    {
         return Content("Successfully updated");
    }
    else
    {
         return Json(new { success = false, message = "Error!"});
    }

然后在OnSuccess JS函数中:

function OnSuccess(data) {
        if (data.success === false){
             alert(data.message);
             $("#Content").html(data.message);
        }
        else
             $("#Content").html(data);

}