1
0
mirror of https://github.com/rudollee/LearningMVC.git synced 2026-08-11 08:22:53 +00:00

Ch. 23 URL and Ajax Helper Methods

This commit is contained in:
wook
2017-04-18 03:33:17 +09:00
parent dabe7ab03e
commit 696951de89
18 changed files with 21654 additions and 0 deletions
@@ -0,0 +1,103 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HelperMethods.Models;
namespace HelperMethods.Controllers
{
public class PeopleController : Controller
{
private Person[] personData =
{
new Person {FirstName = "Adam", LastName = "Freeman", Role = Role.Admin},
new Person {FirstName = "Jacqui", LastName = "Friffyth", Role = Role.User},
new Person {FirstName = "John", LastName = "Smith", Role = Role.User},
new Person {FirstName = "Anne", LastName = "Jones", Role = Role.Guest}
};
public ActionResult Index()
{
return View();
}
//public ActionResult GetPeople()
//{
// return View(personData);
//}
//[HttpPost]
//public ActionResult GetPeople(string selectedRole)
//{
// if (selectedRole == null || selectedRole == "All")
// {
// return View(personData);
// }
// else
// {
// Role selected = (Role)Enum.Parse(typeof(Role), selectedRole);
// return View(personData.Where(p => p.Role == selected));
// }
//}
//private IEnumerable<Person> GetData(string selectedRole)
//{
// IEnumerable<Person> data = personData;
// if (selectedRole != "All")
// {
// Role selected = (Role)Enum.Parse(typeof(Role), selectedRole);
// data = personData.Where(p => p.Role == selected);
// }
// return data;
//}
//public JsonResult GetPeopleDataJson(string selectedRole = "All")
//{
// var data = GetData(selectedRole).Select(p => new
// {
// FirstName = p.FirstName,
// LastName = p.LastName,
// Role = Enum.GetName(typeof(Role), p.Role)
// });
// //IEnumerable<Person> data = GetData(selectedRole);
// return Json(data, JsonRequestBehavior.AllowGet);
//}
//public PartialViewResult GetPeopleData(string selectedRole = "All")
//{
// return PartialView(GetData(selectedRole));
//}
public ActionResult GetPeopleData(string selectedRole = "All")
{
IEnumerable<Person> data = personData;
if (selectedRole != "All")
{
Role selected = (Role)Enum.Parse(typeof(Role), selectedRole);
data = personData.Where(p => p.Role == selected);
}
if (Request.IsAjaxRequest())
{
var formattedData = data.Select(p => new
{
FirstName = p.FirstName,
LastName = p.LastName,
Role = Enum.GetName(typeof(Role), p.Role)
});
return Json(formattedData, JsonRequestBehavior.AllowGet);
}
else
{
return PartialView(data);
}
}
public ActionResult GetPeople(string selectedRole = "All")
{
return View((object)selectedRole);
}
}
}
+6
View File
@@ -98,16 +98,22 @@
<None Include="Scripts\jquery-1.10.2.intellisense.js" />
<Content Include="Scripts\jquery-1.10.2.js" />
<Content Include="Scripts\jquery-1.10.2.min.js" />
<Content Include="Scripts\jquery.unobtrusive-ajax.js" />
<Content Include="Scripts\jquery.unobtrusive-ajax.min.js" />
<Content Include="Scripts\modernizr-2.6.2.js" />
<Content Include="Web.config" />
<Content Include="Views\Home\DisplayPerson.cshtml" />
<Content Include="Views\Shared\EditorTemplates\Role.cshtml" />
<Content Include="Views\Shared\EditorTemplates\Enum.cshtml" />
<Content Include="Views\Shared\EditorTemplates\Boolean.cshtml" />
<Content Include="Views\People\Index.cshtml" />
<Content Include="Views\People\GetPeople.cshtml" />
<Content Include="Views\People\GetPeopleData.cshtml" />
</ItemGroup>
<ItemGroup>
<Compile Include="App_Start\RouteConfig.cs" />
<Compile Include="Controllers\HomeController.cs" />
<Compile Include="Controllers\PeopleController.cs" />
<Compile Include="Global.asax.cs">
<DependentUpon>Global.asax</DependentUpon>
</Compile>
+189
View File
@@ -0,0 +1,189 @@
/* NUGET: BEGIN LICENSE TEXT
*
* Microsoft grants you the right to use these script files for the sole
* purpose of either: (i) interacting through your browser with the Microsoft
* website or online service, subject to the applicable licensing or use
* terms; or (ii) using the files as included with a Microsoft product subject
* to that product's license terms. Microsoft reserves all other rights to the
* files not expressly granted by Microsoft, whether by implication, estoppel
* or otherwise. Insofar as a script file is dual licensed under GPL,
* Microsoft neither took the code under GPL nor distributes it thereunder but
* under the terms set out in this paragraph. All notices and licenses
* below are for informational purposes only.
*
* NUGET: END LICENSE TEXT */
/*!
** Unobtrusive Ajax support library for jQuery
** Copyright (C) Microsoft Corporation. All rights reserved.
*/
/*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */
/*global window: false, jQuery: false */
(function ($) {
var data_click = "unobtrusiveAjaxClick",
data_target = "unobtrusiveAjaxClickTarget",
data_validation = "unobtrusiveValidation";
function getFunction(code, argNames) {
var fn = window, parts = (code || "").split(".");
while (fn && parts.length) {
fn = fn[parts.shift()];
}
if (typeof (fn) === "function") {
return fn;
}
argNames.push(code);
return Function.constructor.apply(null, argNames);
}
function isMethodProxySafe(method) {
return method === "GET" || method === "POST";
}
function asyncOnBeforeSend(xhr, method) {
if (!isMethodProxySafe(method)) {
xhr.setRequestHeader("X-HTTP-Method-Override", method);
}
}
function asyncOnSuccess(element, data, contentType) {
var mode;
if (contentType.indexOf("application/x-javascript") !== -1) { // jQuery already executes JavaScript for us
return;
}
mode = (element.getAttribute("data-ajax-mode") || "").toUpperCase();
$(element.getAttribute("data-ajax-update")).each(function (i, update) {
var top;
switch (mode) {
case "BEFORE":
top = update.firstChild;
$("<div />").html(data).contents().each(function () {
update.insertBefore(this, top);
});
break;
case "AFTER":
$("<div />").html(data).contents().each(function () {
update.appendChild(this);
});
break;
case "REPLACE-WITH":
$(update).replaceWith(data);
break;
default:
$(update).html(data);
break;
}
});
}
function asyncRequest(element, options) {
var confirm, loading, method, duration;
confirm = element.getAttribute("data-ajax-confirm");
if (confirm && !window.confirm(confirm)) {
return;
}
loading = $(element.getAttribute("data-ajax-loading"));
duration = parseInt(element.getAttribute("data-ajax-loading-duration"), 10) || 0;
$.extend(options, {
type: element.getAttribute("data-ajax-method") || undefined,
url: element.getAttribute("data-ajax-url") || undefined,
cache: !!element.getAttribute("data-ajax-cache"),
beforeSend: function (xhr) {
var result;
asyncOnBeforeSend(xhr, method);
result = getFunction(element.getAttribute("data-ajax-begin"), ["xhr"]).apply(element, arguments);
if (result !== false) {
loading.show(duration);
}
return result;
},
complete: function () {
loading.hide(duration);
getFunction(element.getAttribute("data-ajax-complete"), ["xhr", "status"]).apply(element, arguments);
},
success: function (data, status, xhr) {
asyncOnSuccess(element, data, xhr.getResponseHeader("Content-Type") || "text/html");
getFunction(element.getAttribute("data-ajax-success"), ["data", "status", "xhr"]).apply(element, arguments);
},
error: function () {
getFunction(element.getAttribute("data-ajax-failure"), ["xhr", "status", "error"]).apply(element, arguments);
}
});
options.data.push({ name: "X-Requested-With", value: "XMLHttpRequest" });
method = options.type.toUpperCase();
if (!isMethodProxySafe(method)) {
options.type = "POST";
options.data.push({ name: "X-HTTP-Method-Override", value: method });
}
$.ajax(options);
}
function validate(form) {
var validationInfo = $(form).data(data_validation);
return !validationInfo || !validationInfo.validate || validationInfo.validate();
}
$(document).on("click", "a[data-ajax=true]", function (evt) {
evt.preventDefault();
asyncRequest(this, {
url: this.href,
type: "GET",
data: []
});
});
$(document).on("click", "form[data-ajax=true] input[type=image]", function (evt) {
var name = evt.target.name,
target = $(evt.target),
form = $(target.parents("form")[0]),
offset = target.offset();
form.data(data_click, [
{ name: name + ".x", value: Math.round(evt.pageX - offset.left) },
{ name: name + ".y", value: Math.round(evt.pageY - offset.top) }
]);
setTimeout(function () {
form.removeData(data_click);
}, 0);
});
$(document).on("click", "form[data-ajax=true] :submit", function (evt) {
var name = evt.currentTarget.name,
target = $(evt.target),
form = $(target.parents("form")[0]);
form.data(data_click, name ? [{ name: name, value: evt.currentTarget.value }] : []);
form.data(data_target, target);
setTimeout(function () {
form.removeData(data_click);
form.removeData(data_target);
}, 0);
});
$(document).on("submit", "form[data-ajax=true]", function (evt) {
var clickInfo = $(this).data(data_click) || [],
clickTarget = $(this).data(data_target),
isCancel = clickTarget && clickTarget.hasClass("cancel");
evt.preventDefault();
if (!isCancel && !validate(this)) {
return;
}
asyncRequest(this, {
url: this.action,
type: this.method || "GET",
data: clickInfo.concat($(this).serializeArray())
});
});
}(jQuery));
+19
View File
@@ -0,0 +1,19 @@
/* NUGET: BEGIN LICENSE TEXT
*
* Microsoft grants you the right to use these script files for the sole
* purpose of either: (i) interacting through your browser with the Microsoft
* website or online service, subject to the applicable licensing or use
* terms; or (ii) using the files as included with a Microsoft product subject
* to that product's license terms. Microsoft reserves all other rights to the
* files not expressly granted by Microsoft, whether by implication, estoppel
* or otherwise. Insofar as a script file is dual licensed under GPL,
* Microsoft neither took the code under GPL nor distributes it thereunder but
* under the terms set out in this paragraph. All notices and licenses
* below are for informational purposes only.
*
* NUGET: END LICENSE TEXT */
/*
** Unobtrusive Ajax support library for jQuery
** Copyright (C) Microsoft Corporation. All rights reserved.
*/
(function(a){var b="unobtrusiveAjaxClick",d="unobtrusiveAjaxClickTarget",h="unobtrusiveValidation";function c(d,b){var a=window,c=(d||"").split(".");while(a&&c.length)a=a[c.shift()];if(typeof a==="function")return a;b.push(d);return Function.constructor.apply(null,b)}function e(a){return a==="GET"||a==="POST"}function g(b,a){!e(a)&&b.setRequestHeader("X-HTTP-Method-Override",a)}function i(c,b,e){var d;if(e.indexOf("application/x-javascript")!==-1)return;d=(c.getAttribute("data-ajax-mode")||"").toUpperCase();a(c.getAttribute("data-ajax-update")).each(function(f,c){var e;switch(d){case"BEFORE":e=c.firstChild;a("<div />").html(b).contents().each(function(){c.insertBefore(this,e)});break;case"AFTER":a("<div />").html(b).contents().each(function(){c.appendChild(this)});break;case"REPLACE-WITH":a(c).replaceWith(b);break;default:a(c).html(b)}})}function f(b,d){var j,k,f,h;j=b.getAttribute("data-ajax-confirm");if(j&&!window.confirm(j))return;k=a(b.getAttribute("data-ajax-loading"));h=parseInt(b.getAttribute("data-ajax-loading-duration"),10)||0;a.extend(d,{type:b.getAttribute("data-ajax-method")||undefined,url:b.getAttribute("data-ajax-url")||undefined,cache:!!b.getAttribute("data-ajax-cache"),beforeSend:function(d){var a;g(d,f);a=c(b.getAttribute("data-ajax-begin"),["xhr"]).apply(b,arguments);a!==false&&k.show(h);return a},complete:function(){k.hide(h);c(b.getAttribute("data-ajax-complete"),["xhr","status"]).apply(b,arguments)},success:function(a,e,d){i(b,a,d.getResponseHeader("Content-Type")||"text/html");c(b.getAttribute("data-ajax-success"),["data","status","xhr"]).apply(b,arguments)},error:function(){c(b.getAttribute("data-ajax-failure"),["xhr","status","error"]).apply(b,arguments)}});d.data.push({name:"X-Requested-With",value:"XMLHttpRequest"});f=d.type.toUpperCase();if(!e(f)){d.type="POST";d.data.push({name:"X-HTTP-Method-Override",value:f})}a.ajax(d)}function j(c){var b=a(c).data(h);return!b||!b.validate||b.validate()}a(document).on("click","a[data-ajax=true]",function(a){a.preventDefault();f(this,{url:this.href,type:"GET",data:[]})});a(document).on("click","form[data-ajax=true] input[type=image]",function(c){var g=c.target.name,e=a(c.target),f=a(e.parents("form")[0]),d=e.offset();f.data(b,[{name:g+".x",value:Math.round(c.pageX-d.left)},{name:g+".y",value:Math.round(c.pageY-d.top)}]);setTimeout(function(){f.removeData(b)},0)});a(document).on("click","form[data-ajax=true] :submit",function(e){var g=e.currentTarget.name,f=a(e.target),c=a(f.parents("form")[0]);c.data(b,g?[{name:g,value:e.currentTarget.value}]:[]);c.data(d,f);setTimeout(function(){c.removeData(b);c.removeData(d)},0)});a(document).on("submit","form[data-ajax=true]",function(h){var e=a(this).data(b)||[],c=a(this).data(d),g=c&&c.hasClass("cancel");h.preventDefault();if(!g&&!j(this))return;f(this,{url:this.action,type:this.method||"GET",data:e.concat(a(this).serializeArray())})})})(jQuery);
@@ -0,0 +1,65 @@
@using HelperMethods.Models
@model string
@{
ViewBag.Title = "GetPeople";
Layout = "/Views/Shared/_Layout.cshtml";
AjaxOptions ajaxOpts = new AjaxOptions {
UpdateTargetId = "tableBody",
Url = Url.Action("GetPeopleData"),
LoadingElementId = "loading",
LoadingElementDuration = 1000
//Confirm = "Do you wish to request new data?"
};
}
<script type="text/javascript">
function processData(data) {
var target = $("#tableBody");
target.empty();
for (var i = 0; i < data.length; i++) {
var person = data[i];
target.append("<tr><td>" + person.FirstName + "</td><td>" + person.LastName + "</td><td>" + person.Role + "</td></tr>");
}
}
</script>
<h2>GetPeople</h2>
<div id="loading" class="load" style="display: none;">
<p>Loading Data...</p>
</div>
<table>
<thead><tr><th>First</th><th>Last</th><th>Role</th></tr></thead>
<tbody id="tableBody">
@*@foreach (Person p in Model)
{
<tr>
<td>@p.FirstName</td>
<td>@p.LastName</td>
<td>@p.Role</td>
</tr>
}*@
@Html.Action("GetPeopleData", new { selectedRole = Model})
</tbody>
</table>
@using (Ajax.BeginForm("GetPeopleData", ajaxOpts))
{
<div>
@Html.DropDownList("selectedRole", new SelectList( new[] { "All" }.Concat(Enum.GetNames(typeof(Role)))))
<button type="submit">Submit</button>
</div>
}
<div>
@foreach (string role in Enum.GetNames(typeof(Role)))
{
<div class="ajaxLink">
@Ajax.ActionLink(role, "GetPeopleData",
new { selectedRole = role },
new AjaxOptions { UpdateTargetId = "tableBody", Url = Url.Action("GetPeopleData", new { SelectedRole = role }), OnSuccess = "processData"})
</div>
}
</div>
@@ -0,0 +1,12 @@
@using HelperMethods.Models
@model IEnumerable<Person>
@foreach (Person p in Model)
{
<tr>
<td>@p.FirstName</td>
<td>@p.LastName</td>
<td>@p.Role</td>
</tr>
}
+37
View File
@@ -0,0 +1,37 @@
@{
ViewBag.Title = "Index";
Layout = "/Views/Shared/_Layout.cshtml";
}
<h2>Basic Links</h2>
<table>
<thead><tr><th>Helper</th><th>Output</th></tr></thead>
<tbody>
<tr>
<td>Url.Content("~/Content/Site.css")</td>
<td>@Url.Content("~/Content/Site.css")</td>
</tr>
<tr>
<td>Html.ActionLink("My Link", "Index", "Home")</td>
<td>@Html.ActionLink("My Link", "Index", "Home")</td>
</tr>
<tr>
<td>Url.Action("GetPeople", "People")</td>
<td>@Url.Action("GetPeople", "People")</td>
</tr>
<tr>
<td>Url.RouteUrl(new { controller = "People", action = "Getpeople" })</td>
<td>@Url.RouteUrl(new { controller = "People", action = "Getpeople" })</td>
</tr>
<tr>
<td>Html.RouteLink("My Link", new { Controller = "Poeple", action = "GetPeople" })</td>
<td>@Html.RouteLink("My Link", new { Controller = "Poeple", action = "GetPeople" })</td>
</tr>
<tr>
<td>Html.RouteLink("My Link", "FormRoute", new { controller = "People", action = "GetPeople" })</td>
<td>@Html.RouteLink("My Link", "FormRoute", new { controller = "People", action = "GetPeople" })</td>
</tr>
</tbody>
</table>
@@ -14,7 +14,14 @@
.editor-field { margin-left: 10px; }
input[type=submit] { float: left; clear: both; margin-top: 10px;}
.column { float: left; margin: 10px;}
table, td, th {border: thin solid black; border-collapse: collapse;
padding: 5px; background-color: lemonchiffon;
text-align: left; margin: 10px 0;}
div.load { color: red; margin: 10px 0; font-weight: bold; }
div.ajaxLink { margin-top: 10px; margin-right: 5px; float: left; }
</style>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"> </script>
</head>
<body>
@RenderBody()
+1
View File
@@ -6,6 +6,7 @@
<package id="Microsoft.AspNet.Razor" version="3.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebPages" version="3.2.3" targetFramework="net452" />
<package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.3" targetFramework="net452" />
<package id="Microsoft.jQuery.Unobtrusive.Ajax" version="3.2.3" targetFramework="net452" />
<package id="Microsoft.Net.Compilers" version="1.3.2" targetFramework="net452" developmentDependency="true" />
<package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net452" />
<package id="Modernizr" version="2.6.2" targetFramework="net452" />