2013-03-14 25 views
0

我是新手在MVC3。我在'編輯'視圖上有一個按鈕[生成密碼]。我需要在'Admin'控制器中執行一個函數Ge​​neratePsw(),該函數在顯示一個包含由GeneratePsw()返回的值的模態之前返回一個字符串。MVC3&Bootstrap - 執行功能之前顯示引導模式

我也嘗試將該值放入ViewBag.pwd中,而不是將其返回並從模態中讀取。沒有成功

換句話說:

用戶不要點擊[Generate Password]按鈕。然後調用GeneratePsw()並返回一個字符串。 Bootstrap模式應該會自動在標籤中顯示該值。

在我看來.....

<a href="#1" role="button" class="btn btn-primary btn-small" data-toggle="modal" onclick="location.href='@Url.Action("GeneratePsw", "Admin")';return false;"><i class="icon-lock icon-white"></i> Generate Password</a> 


</div> 


<div id="1" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"> 
<div class="modal-header"> 
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> 
     <h3 id="myModalLabel">Password generated</h3> 
</div> 
<div class="modal-body"> 
     <p><strong>Password: @(ViewBag.pwd)</strong></p> 
    </div> 
    <div class="modal-footer"> 
     <button class="btn" data-dismiss="modal" aria-hidden="true">OK</button> 

    </div> 
</div> 


</td> 

我GeneratePsw()函數:

[HttpPost] 
public ActionResult GeneratePsw() 
{ 

    HomeBridgeEntities ddbb = new HomeBridgeEntities(); 
    SqlConnection Cn = new SqlConnection(((System.Data.EntityClient.EntityConnection)ddbb.Connection).StoreConnection.ConnectionString); 
    SupPassGenerator sup = new SupPassGenerator(Cn); 

    string psw = sup.CreateRandomPassword(9); 

    ViewBag.psw = psw; 

    return RedirectToAction("Edit"); 

} 

回答

1

所以我的理解是,要做到這一點作爲一個Ajax調用?即不重新加載整個頁面?我也假設你正在使用jQuery?

你可以通過回發到你的控制器來返回JSON。這可能是把它找回來最簡單的方法:

控制器:

public ActionResult GeneratePsw() 
{ 
    ... 
    string psw = sup.CreateRandomPassword(9); 
    var json = new { password = psw }; 
    return Json(json); 
} 

頁面上的JS:

$('#yourgeneratebutton').on('click', function() { 
    $.getJSON('YourController/GeneratePsw', function(data) { 
     $('#yourpasswordp').text(data.password); 
     $('#1').modal('show'); 
    }); 

注意,我使用getJSON,所以你可以不裝飾與HttpPost的行動。 (你還沒有發佈任何數據?你要麼改變http屬性,要麼改爲使用$.post,這也是完全沒有經過測試的,只是一個粗略的指南。

或者,一個替代可能是返回一個部分視圖,它有模態的東西,然後顯示。

+0

+1非常感謝你!!這正是我需要的!現在工作很好,謝謝你! – equisde 2013-03-15 13:35:20