mvc 4 Ajax and jQuery
第一种方法:
1:带ajax请求创建一个链接
@Ajax.ActionLink("This is an Ajax link", "actionName", "controllerName", ajaxOptions)
<div id="petPhoto">
@Ajax.ActionLink("Display pet picture", "GetPhoto", "Pet",
new RouteValueDictionary { {"id",ViewBag.PetName } },
new AjaxOptions
{
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
LoadingElementId = "loadingPhoto",
UpdateTargetId = "petPhoto"
})
</div>
<div id="loadingPhoto" style="display:none">
Loading Pet...
</div>
后台:
public ActionResult Send()
{
var name = (string)RouteData.Values["id"];
ViewBag.PetName = name;
ViewBag.IsSent = false;
return View();
}
2:Creating Ajax Forms
<div id="messageForm">
<h2>Send Message</h2>
@using (Ajax.BeginForm(new AjaxOptions
{
Confirm = "Are you sure you want to send this message?",
HttpMethod = "Post",
InsertionMode = InsertionMode.Replace,
LoadingElementId = "loading",
UpdateTargetId = "messageForm",
OnBegin = "beginRequest",
OnComplete = "endRequest"
}))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>MessageModel</legend>
<div class="editor-label">
@Html.LabelFor(model => model.From)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.From)
@Html.ValidationMessageFor(model => model.From)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Email)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Subject)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Subject)
@Html.ValidationMessageFor(model => model.Subject)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Message)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Message)
@Html.ValidationMessageFor(model => model.Message)
</div>
<p>
<input type="submit" value="Send Message" />
</p>
</fieldset>
}
</div>
<div id="loading" style="display:none">
Sending Message...
</div>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
<script>
function beginRequest() {
$("#messageForm").hide();
}
function endRequest(request, status) {
$("#messageForm").show();
}
</script>
}
Implementing Ajax Callbacks
3:Making Ajax Requests Directly with jQuery
$.ajax ({
url : "",
type: ""
data: "",
dataType: "",
beforeSend: handler,
complete: handler,
success: handler,
error: handler
});


得到json数据
public JsonResult GetInfo()
{
var name = (string)RouteData.Values["id"];
var pet = PetManagement.GetByName(name);
return Json(pet, JsonRequestBehavior.AllowGet);
}
var menuId = $( "ul.nav" ).first().attr( "id" );var request = $.ajax({ url: "script.php", type: "POST", data: { id : menuId }, dataType: "html"});request.done(function( msg ) { $( "#log" ).html( msg );});request.fail(function( jqXHR, textStatus ) { alert( "Request failed: " + textStatus );});
浙公网安备 33010602011771号