ASP.NET MVC #21
نویسنده: وحید نصیری
تاریخ: ۱۳۹۱/۰۲/۰۵ ۱۷:۴۸:۰۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
using System;
namespace System.Web.Mvc
{
public abstract class WebViewPage<TModel> : WebViewPage
{
protected WebViewPage();
public AjaxHelper<TModel> Ajax { get; set; }
public HtmlHelper<TModel> Html { get; set; }
public TModel Model { get; }
public ViewDataDictionary<TModel> ViewData { get; set; }
public override void InitHelpers();
protected override void SetViewData(ViewDataDictionary viewData);
}
}
<head>
<title>@ViewBag.Title</title>
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
</head>
namespace MvcApplication18.Models
{
public class Employee
{
public int Id { set; get; }
public string Name { set; get; }
}
}
using System.Collections.Generic;
namespace MvcApplication18.Models
{
public static class EmployeeDataSource
{
public static IList<Employee> CreateEmployees()
{
var list = new List<Employee>();
for (int i = 0; i < 1000; i++)
{
list.Add(new Employee { Id = i + 1, Name = "name " + i });
}
return list;
}
}
}
using System.Linq;
using System.Web.Mvc;
using MvcApplication18.Models;
namespace MvcApplication18.Controllers
{
public class HomeController : Controller
{
[HttpGet]
public ActionResult Index()
{
return View();
}
[HttpPost] //for IE-8
public ActionResult EmployeeInfo(int? id)
{
if (!Request.IsAjaxRequest())
return View("Error");
if (!id.HasValue)
return View("Error");
var list = EmployeeDataSource.CreateEmployees();
var data = list.Where(x => x.Id == id.Value).FirstOrDefault();
if (data == null)
return View("Error");
return PartialView(viewName: "_EmployeeInfo", model: data);
}
}
}
@model MvcApplication18.Models.Employee
<strong>Name:</strong> @Model.Name
@{
ViewBag.Title = "Index";
}
<h2>
Index</h2>
<div id="EmployeeInfo">
@Ajax.ActionLink(
linkText: "Get Employee-1 info",
actionName: "EmployeeInfo",
controllerName: "Home",
routeValues: new { id = 1 },
ajaxOptions: new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "EmployeeInfo",
LoadingElementId = "Progress"
})
</div>
<div id="Progress" style="display: none">
<img src="@Url.Content("~/Content/images/loading.gif")" alt="loading..." />
</div>
[AttributeUsage(AttributeTargets.Class|AttributeTargets.Method)]
public class AjaxOnlyAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
base.OnActionExecuting(filterContext);
}
else
{
throw new InvalidOperationException("This operation can only be accessed via Ajax requests");
}
}
}
[AjaxOnly]
public ActionResult SomeAjaxAction()
{
return Content("Hello!");
}
<a data-ajax="true" data-ajax-loading="#Progress" data-ajax-method="POST"
data-ajax-mode="replace" data-ajax-update="#EmployeeInfo"
href="/Home/EmployeeInfo/1">Get Employee-1 info</a>
<a href="#" onclick="LoadEmployeeInfo()">Get Employee-1 info</a>
@section javascript
{
<script type="text/javascript">
function LoadEmployeeInfo() {
showProgress();
$.ajax({
type: "POST",
url: "/Home/EmployeeInfo",
data: JSON.stringify({ id: 1 }),
contentType: "application/json; charset=utf-8",
dataType: "json",
// controller is returning a simple text, not json
complete: function (xhr, status) {
var data = xhr.responseText;
if (status === 'error' || !data) {
//handleError
}
else {
$('#EmployeeInfo').html(data);
}
hideProgress();
}
});
}
function showProgress() {
$('#Progress').css("display", "block");
}
function hideProgress() {
$('#Progress').css("display", "none");
}
</script>
}
@RenderSection("javascript", required: false)
[HttpPost] //for IE-8
public ActionResult EmployeeInfoData(int? id)
{
if (!Request.IsAjaxRequest())
return Json(false);
if (!id.HasValue)
return Json(false);
var list = EmployeeDataSource.CreateEmployees();
var data = list.Where(x => x.Id == id.Value).FirstOrDefault();
if (data == null)
return Json(false);
return Json(data);
}
<a href="#" onclick="LoadEmployeeInfoData()">Get Employee-2 info</a>
@section javascript
{
<script type="text/javascript">
function LoadEmployeeInfoData() {
showProgress();
$.ajax({
type: "POST",
url: "/Home/EmployeeInfoData",
data: JSON.stringify({ id: 1 }),
contentType: "application/json; charset=utf-8",
dataType: "json",
// controller is returning the json data
success: function (result) {
if (result) {
alert(result.Id + ' - ' + result.Name);
}
hideProgress();
},
error: function (result) {
alert(result.status + ' ' + result.statusText);
hideProgress();
}
});
}
function showProgress() {
$('#Progress').css("display", "block");
}
function hideProgress() {
$('#Progress').css("display", "none");
}
</script>
}
[HttpPost] //for IE-8
public ActionResult SearchEmployeeInfo(string data)
{
if (!Request.IsAjaxRequest())
return Content(string.Empty);
if (string.IsNullOrWhiteSpace(data))
return Content(string.Empty);
var employeesList = EmployeeDataSource.CreateEmployees();
var list = employeesList.Where(x => x.Name.Contains(data)).ToList();
if (list == null || !list.Any())
return Content(string.Empty);
return PartialView(viewName: "_SearchEmployeeInfo", model: list);
}
@model IEnumerable<MvcApplication18.Models.Employee>
<table>
<tr>
<th>
Name
</th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
</tr>
}
</table>
@using (Ajax.BeginForm(actionName: "SearchEmployeeInfo",
controllerName: "Home",
ajaxOptions: new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "EmployeeInfo",
LoadingElementId = "Progress"
}))
{
@Html.TextBox("data")
<input type="submit" value="Search" />
}
<form action="/Home/SearchEmployeeInfo" data-ajax="true"
data-ajax-loading="#Progress" data-ajax-method="POST"
data-ajax-mode="replace" data-ajax-update="#EmployeeInfo"
id="form0" method="post">
<input id="data" name="data" type="text" value="" />
<input type="submit" value="Search" />
</form>
$.validator.unobtrusive.parse("#{form-id}");
$.ajax
({
url: "/{controller}/{action}/{id}",
type: "get",
success: function(data)
{
$.validator.unobtrusive.parse("#{form-id}");
}
});
//or
$.get('/{controller}/{action}/{id}', function (data) { $.validator.unobtrusive.parse("#{form-id}"); });
@using (Ajax.BeginForm(
"Action1",
"Controller",
null,
new AjaxOptions {
OnSuccess = "onSuccess",
UpdateTargetId = "result"
},
null)
)
{
<input type="submit" value="Save" />
}
var onSuccess = function(result) {
// enable unobtrusive validation for the contents
// that was injected into the <div id="result"></div> node
$.validator.unobtrusive.parse("#result");
};
@{
var postUrl = Url.Action(actionName: "Delete", controllerName: "Student");
}
<div class="deleteDialog">
<div>
آیتمهای انتخاب شده حذف خواهند شد. آیا تأیید میکنید؟
</div>
<p>
<input type="submit" id="btn_SubmitDelete" value="حذف" />
<input type="submit" id="btn_CancelDelete" value="انصراف" />
</p>
</div>
<script type="text/javascript">
$(function () {
$("#btn_SubmitDelete").click(function (e) {
var button = $(this);
e.preventDefault();
var data = "1,3,8,9";
$.ajax({
type: "POST",
url: "@postUrl",
data: JSON.stringify({ ids: data}),
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false,
beforeSend: function () { },
success: function (html) {
alert(html);
$(".deleteDialog").parent("div").css("display", "none");
},
complete: function () {
button.removeAttr('disabled');
button.val("حذف");
}
});
});
$("#btn_CancelDelete").click(function (e) {
e.preventDefault();
var button = $(this);
$(".deleteDialog").parent("div").css("display", "none");
});
});
</script>[HttpGet]
public ActionResult Delete()
{
return PartialView("Pv_Delete");
}
[HttpPost]
[AjaxOnly]
public ActionResult Delete(string ids)
{
var allIds = ids.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList();
Thread.Sleep(2000);
if (true)
{
return Json(new { result = "ok" }, JsonRequestBehavior.AllowGet);
}
return Json(new { result = "error" });
}سلام
خسته نباشید
در مقالتون فرمودین بجای Ajax.BeginForm میتوان از $.ajax استفاده نمود . اما در ستفاده از Ajax داده به صورت دستی در پارامتر Data پاس داده شده . آیا امکان این هست که Ajax را همانند Ajax.Beginform دات نت پیاده سازی کرد تا با Post شدن فرم اطلاعات اتوماتیک و بدون مقدار دهی پارامتر مذکور ارسال شود.
چرا که من در فرم، فایل آپلود میکنم ولی کتابخانه unobtrusive با HttpPostFileBase مشکل داره و میخوام از Helper دت نت استفاده نکنم و مستقیما از Ajax و بدون کتابخانه ذکر شده استفاده کنم.
در این خصوص نظر شما چیه ؟ آیا کاری که من به سبب مشکلی که در آپلود فایل در Helperهای Ajax دارم صحیح است؟
var onSuccess = function(result) {
// enable unobtrusive validation for the contents
// that was injected into the <div id="result"></div> node
$.validator.unobtrusive.parse("#result");
};@model MvcApplication1.Models.Com
<script>
var onSuccess = function (result) {
$.validator.unobtrusive.parse("#result");
};
</script>
<div id="result" >
@using (Ajax.BeginForm(
"SendCommentAction",
"Home",
null,
new AjaxOptions {
OnSuccess = "onSuccess",
UpdateTargetId = "result"
},
null)
)
{
@Html.TextBoxFor(x=>x.Contect) <br/>
@Html.ValidationMessageFor(x=>x.Contect)
<br/>
@Html.ValidationSummary()
<input type="submit" value="Save" />
}
</div> @Ajax.ActionLink("Test",
"action",
new AjaxOptions { HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "UserDiv",
OnSuccess="$.validator.unobtrusive.parse('#my_form_id');"
}
) <script type="text/javascript">
$.validator.unobtrusive.parse("#my_frm_id");
</script> <script type="text/javascript">
$(function () {
getData();
});
function getData() {
var $tbl = $('#tblEmployee');
$.ajax({
url: 'Home/EmployeeInfoData',
type: 'Post',
datatype: 'json',
success: function (data) {
if (data.length > 0) {
$tbl.empty();
$tbl.append(' <tr><th>ID</th><th>Name</th><th>Family</th></tr>');
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push(' <tr><td>' + data[i].Id + '</td><td>' + data[i].Name + '</td><td>' + data[i].Family + '</td></tr>');
}
$tbl.append(rows.join(''));
}
}
});
}
</script> [HttpPost]
public ActionResult EmployeeInfoData()
{
InfoEmployee mp = new InfoEmployee();
var names = mp.GetData();
return Json(names);
} NetworkError: 404 Not Found - http://localhost:9303/Home/Home/EmployeeInfoData
@using(Ajax.BeginForm(MVC.Post.ActionNames.New ,
MVC.Post.Name,
new AjaxOptions(){
HttpMethod = "Post" ,
Confirm ="$.prompt('درخواست تایید - موافقید ؟',{prefix: 'dnt',buttons: { 'تایید': true, 'انصراف': false }});" })) @using(Ajax.BeginForm(MVC.Post.ActionNames.New ,
MVC.Post.Name,
new AjaxOptions(){
HttpMethod = "Post" ,
OnSuccess = "var noty = window.noty({ text: 'نظر شما ثبت شد بعد از تایید نمایش داده میشود', type: 'success', layout: 'center', timeout: 4000 });"
}))