您可以使用jquery UI Dialog作爲彈出窗口。讓我們在這裏做一個小設置。
我們將不得不爲主要形式的視圖模型:
public class MyViewModel
{
public string ValueId { get; set; }
public IEnumerable<SelectListItem> Values
{
get
{
return new[]
{
new SelectListItem { Value = "1", Text = "item 1" },
new SelectListItem { Value = "2", Text = "item 2" },
new SelectListItem { Value = "3", Text = "item 3" },
};
}
}
public string NewValue { get; set; }
}
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return Content("thanks for submitting");
}
}
的圖,(~/Views/Home/Index.aspx
):
<%@ Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<AppName.Models.MyViewModel>"
%>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) { %>
<%= Html.DropDownListFor(x => x.ValueId, Model.Values) %>
<br/>
<%= Html.EditorFor(x => x.NewValue) %>
<%= Html.ActionLink("Suggest Value", "New", "NewValue", null, new { id = "new-value-link" }) %>
<button type="submit">OK</button>
<% } %>
<div id="dialog"></div>
</asp:Content>
那麼我們可以採取關心彈出窗口。我們定義了一個視圖模型爲它:
public class NewValueViewModel
{
public string Foo { get; set; }
public string Bar { get; set; }
}
控制器:
public class NewValueController : Controller
{
public ActionResult New()
{
return PartialView(new NewValueViewModel());
}
[HttpPost]
public ActionResult New(NewValueViewModel model)
{
var newValue = string.Format("{0} - {1}", model.Foo, model.Bar);
return Json(new { newValue = newValue });
}
}
和相應的局部視圖(~/Views/NewValue/New.ascx
):
<%@ Control
Language="C#"
Inherits="System.Web.Mvc.ViewUserControl<AppName.Models.NewValueViewModel>"
%>
<% using (Html.BeginForm(null, null, FormMethod.Post, new { id = "new-value-form" })) { %>
<%= Html.EditorFor(x => x.Foo) %>
<%= Html.EditorFor(x => x.Bar) %>
<button type="submit">OK</button>
<% } %>
現在,所有剩下的就是寫一個位的JavaScript的電線一切了起來。我們包括jQuery和jQuery用戶界面:
<script src="<%: Url.Content("~/Scripts/jquery-1.5.1.min.js") %>" type="text/javascript"></script>
<script src="<%: Url.Content("~/Scripts/jquery-ui-1.8.11.js") %>" type="text/javascript"></script>
和自定義JavaScript文件,該文件將包含我們的代碼:
$(function() {
$('#new-value-link').click(function() {
var href = this.href;
$('#dialog').dialog({
modal: true,
open: function (event, ui) {
$(this).load(href, function (result) {
$('#new-value-form').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (json) {
$('#dialog').dialog('close');
$('#NewValue').val(json.newValue);
}
});
return false;
});
});
}
});
return false;
});
});
試過,但自動取款機,而不是它的姿態出現,它只是打開一個新一頁。想知道,哪個部分的jquery觸發模態? – gdubs 2012-07-18 13:02:37
這是訂閱鏈接的'.click()'事件。確保你已經正確包含了所有3個JavaScript文件('jquery-1.5.1.min.js','jquery-ui-1.8.11.js'和'my.js') - 包含我在該順序),並在JavaScript控制檯中沒有錯誤。 – 2012-07-18 13:34:35
看到了問題,這是一個額外的'})的cuz;''大聲笑!再次感謝! – gdubs 2012-07-18 21:41:51