我有索引视图:
@using System.Web.Mvc.Html @model MsmqTestApp.Models.MsmqData <!DOCTYPE html> <html> <head> <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script> <Meta name="viewport" content="width=device-width" /> <title>MsmqTest</title> </head> <body> <div> <input type="submit" id="btnBuy" value="Buy" onclick="location.href='@Url.Action("BuyItem","MsmqTest",new { area = "Msmq" })'" /> <input type="submit" id="btnSell" value="Sell" onclick="location.href='@Url.Action("SellItem",new { area = "Msmq" })'" /> </div> <div id="msmqpartial"> @{Html.RenderPartial("Partial1",Model); } </div> </body> </html>
和部分:
@using System.Web.Mvc.Html @model MsmqTestApp.Models.MsmqData <p> Items to buy @foreach (var item in Model.ItemsToBuy) { <tr> <td>@Html.DisplayFor(model => item) </td> </tr> } </p> <p> <a>Items Selled</a> @foreach (var item in Model.ItemsSelled) { <tr> <td>@Html.DisplayFor(model => item) </td> </tr> } </p>
和控制器:
public class MsmqTestController : Controller { public MsmqData data = new MsmqData(); public ActionResult Index() { return View(data); } public ActionResult BuyItem() { PushIntoQueue(); ViewBag.DataBuyCount = data.ItemsToBuy.Count; return PartialView("Partial1",data); } }
如何做到这一点,当我点击一个按钮只是部分视图渲染,现在控制器要移动我到BuyItem视图; /
解决方法
首先要做的是引用jQuery.现在你只引用了jquery.unobtrusive-ajax.min.js,但这个脚本依赖于jQuery,所以不要忘记在它之前包括:
<script src="@Url.Content("~/Scripts/jquery.jquery-1.5.1.min.js")" type="text/javascript"></script> <script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
现在您的问题:您应该使用提交按钮与HTML表单.在你的例子中,你没有一个表单,所以在语义上更正确的是使用普通按钮:
<input type="button" value="Buy" data-url="@Url.Action("BuyItem",new { area = "Msmq" })" /> <input type="button" value="Sell" data-url="@Url.Action("SellItem",new { area = "Msmq" })" />
然后在单独的javascript文件中通过订阅.click()事件AJAXify这些按钮:
$(function() { $(':button').click(function() { $.ajax({ url: $(this).data('url'),type: 'GET',cache: false,success: function(result) { $('#msmqpartial').html(result); } }); return false; }); });
或者如果您想依靠Microsoft不引人注目的框架,您可以使用AJAX actionlinks:
@Ajax.ActionLink("Buy","BuyItem",new { area = "Msmq" },new AjaxOptions { UpdateTargetId = "msmqpartial" }) @Ajax.ActionLink("Sell","SellItem",new AjaxOptions { UpdateTargetId = "msmqpartial" })
如果您想要按钮而不是锚点,您可以使用AJAX表单:
@using (Ajax.BeginForm("BuyItem",new AjaxOptions { UpdateTargetId = "msmqpartial" })) { <button type="submit">Buy</button> } @using (Ajax.BeginForm("SellItem",new AjaxOptions { UpdateTargetId = "msmqpartial" })) { <button type="submit">Sell</button> }
从我可以看到,您已经将jquery.unobtrusive-ajax.min.js脚本包含在您的页面中,这应该是正常的.