2012-04-26 52 views
1

我是新來的MVC3,想知道是否有可能將值返回到模態對話框。見下面的例子。MVC3返回值到模態對話框

在我的.cshtml文件中,當點擊「log」按鈕時,它會調用Log Action。

<button name="button" value="log" id="log">Log</button> 
<div id="dialog-message" title="Input Error!"> 
    <p> 
    <span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span> 
    The result from the controller is : 
    </p> 
</div> 

在我的控制器動作,我有這個

public ActionResult Log(FormCollection collection) 
{ 
    if(x+2!=4) 
    { 
     // return the value of x to the modal dialog 
    } 
    else 
    { 
     // save record to database 
    } 
} 

我想要的jQuery模態窗口顯示x的值。

在jQuery腳本,我有以下

$("#dialog-message").dialog({ 
     autoOpen: false, 
     modal: true, 
     buttons: { 
      Ok: function() { 
       $(this).dialog("close"); 
      } 
     } 
    }); 

    $("#log").click(function() { 
     $("#dialog-message").dialog("open"); 
     this.defaultShowErrors(); 
    }); 

請幫助!

回答

2

看起來你錯過了兩件事:1)結果容器,2)Ajax調用來獲得結果。首先容器:

The result from the controller is : <span id='result_container'></span> 

而Ajax調用:

$("#log").click(function() { 
    var ajaxUrl = // set the URL for **Log** here 
    $.get(ajaxUrl, function(data) { 
     $("#result_container").html(data); 
    }); 
    $("#dialog-message").dialog("open"); 
}); 

在控制器,你只是返回的結果爲純文本:

if(x+2!=4) 
{ 
    // return the value of x to the modal dialog 
    return new ContentResult() { 
     Content = x, 
     ContentEncoding = System.Text.Encoding.UTF8, 
     ContentType = "text/plain" 
    }; 
} 
+0

我剛試過你的解決方案,模態對話框是空的。但是打開一個包含x的值的新頁面。請我需要的是對話框顯示x。謝謝 – 2012-04-26 23:38:29