![]() Главная страница Случайная страница КАТЕГОРИИ: АвтомобилиАстрономияБиологияГеографияДом и садДругие языкиДругоеИнформатикаИсторияКультураЛитератураЛогикаМатематикаМедицинаМеталлургияМеханикаОбразованиеОхрана трудаПедагогикаПолитикаПравоПсихологияРелигияРиторикаСоциологияСпортСтроительствоТехнологияТуризмФизикаФилософияФинансыХимияЧерчениеЭкологияЭкономикаЭлектроника |
Public Language CurrentLang
{ Get { return CurrentUser! = null? CurrentUser.Language: null; } }
protected override void Initialize(RequestContext requestContext) { CultureInfo ci = new CultureInfo(" ru");
Thread.CurrentThread.CurrentCulture = ci; base.Initialize(requestContext); }
} И /Areas/Admin/Controller/HomeController.cs: [Authorize(Roles=" admin")] public class HomeController: AdminController { public ActionResult Index() { return View(); }
public ActionResult AdminMenu() { return View(); }
public ActionResult LangMenu() { if (CurrentLang == null) { var lang = repository.Languages.FirstOrDefault(); repository.ChangeLanguage(currentUser, lang.Code); } var langProxy = new LangAdminView(repository, CurrentLang.Code); return View(langProxy); }
[HttpPost] public ActionResult ChangeLanguage(string SelectedLang) { repository.ChangeLanguage(currentUser, SelectedLang); return Redirect(" ~/admin"); } } Итак, AdminController выбирает и устанавливает, в каком языке мы сейчас работаем. Если данный язык не установлен, то выбирается первый попавшийся, и в HomeController.cs: LangMenu устанавливается для пользователя. Создадим LangAdminView.cs (/Models/ViewModel/LangAdminView.cs): public class LangAdminView { private IRepository Repository { get { return DependencyResolver.Current.GetService< IRepository> (); } }
public string SelectedLang {get; set; }
public List< SelectListItem> Langs { get; set; }
public LangAdminView(string currentLang) { currentLang = currentLang?? " "; Langs = new List< SelectListItem> ();
foreach (var lang in Repository.Languages) { Langs.Add(new SelectListItem() { Selected = (string.Compare(currentLang, lang.Code, true) == 0), Value = lang.Code, Text = lang.Name }); } } } Опишем все View (+js-файлы): /Areas/Admin/Views/Shared/_Layout.cshtml: @{ var currentUser = ((LessonProject.Controllers.BaseController)ViewContext.Controller).CurrentUser; } <! DOCTYPE html> < html> < head> < title> @ViewBag.Title< /title> < meta http-equiv=" Content-Type" content=" text/html; charset=UTF-8" /> @Styles.Render(" ~/Content/css/jqueryui") @Styles.Render(" ~/Content/css") @RenderSection(" styles", required: false) @Scripts.Render(" ~/bundles/modernizr") < /head> < body> < div class=" navbar navbar-fixed-top" > < div class=" navbar-inner" > < div class=" container-fluid" > < div class=" btn-group pull-right" > < a class=" btn dropdown-toggle" data-toggle=" dropdown" href=" #" > < i class=" icon-user" > < /i> @currentUser.Email< span class=" caret" > < /span> < /a> < ul class=" dropdown-menu" > < li> < a href=" /" > На сайт< /a> < /li> < li class=" divider" > < /li> < li> < a href=" @Url.Action(" Logout", " Login", new { area = " Default" })" > Выход< /a> < /li> < /ul> < /div> < a class=" brand" href=" @Url.Action(" Index", " Home")" > LessonProject< /a> < /div> < /div> < /div> < div class=" container-fluid" > < div class=" row-fluid" > < div class=" span3" > < div class=" well sidebar-nav" > < ul class=" nav nav-list" > @Html.Action(" LangMenu", " Home") @Html.Action(" AdminMenu", " Home") < /ul> < /div> < /div> < div class=" span9" > @RenderBody() < /div> < /div> < /div> @Scripts.Render(" ~/bundles/jquery") @Scripts.Render(" ~/bundles/jqueryui") @Scripts.Render(" ~/bundles/bootstrap") @Scripts.Render(" ~/bundles/common") @Scripts.Render(" /Scripts/admin/common.js") @RenderSection(" scripts", required: false) < /body> < /html>
Index.cshtml (/Areas/Admin/Views/Home/Index.cshtml): @{ ViewBag.Title = " Index"; Layout = " ~/Areas/Admin/Views/Shared/_Layout.cshtml"; }
< h2> Админка< /h2>
AdminMenu.cshtml (/Areas/Admin/Views/Home/AdminMenu.cshtml): < li> @Html.ActionLink(" Главная", " Index", " Home") < /li> < li> @Html.ActionLink(" Посты", " Index", " Post") < /li>
LangMenu.cshtml (/Areas/Admin/Views/Home/LangMenu.cshtml): @model LessonProject.Models.ViewModels.LangAdminView
< li> @using (Html.BeginForm(" ChangeLanguage", " Home", FormMethod.Post, new { id = " SelectLangForm" })) { @Html.DropDownList(" SelectedLang", Model.Langs) } < /li>
И обработчик SelectedLang (/Scripts/admin/common.js): function AdminCommon() { _this = this;
this.init = function () { $(" #SelectedLang").change(function () { $(" #SelectLangForm").submit(); }); } }
var adminCommon = null; $().ready(function () { adminCommon = new AdminCommon(); adminCommon.init(); });
Заходим под админом (у меня это chernikov@gmail.com) и переходим на страницу https://localhost/admin: Если не удалось зайти и выкинуло на /Login, то проверьте связь UserRole в БД, чтобы текущий пользователь имел роль с кодом “admin”. Открываем выпадающий список языков. Он и показывает, в каком языке мы в данный момент работаем. Добавляем контроллер PostController.cs (/Areas/Admin/Controllers/PostController.cs): public class PostController: AdminController { public ActionResult Index(int page = 1) { var list = Repository.Posts.OrderByDescending(p => p.AddedDate); var data = new PageableData< Post> (list, page); data.List.ForEach(p => p.CurrentLang = CurrentLang.ID); return View(data); }
[HttpGet] public ActionResult Create() { var postView = new PostView { CurrentLang = CurrentLang.ID }; return View(" Edit", postView); }
[HttpGet] public ActionResult Edit(int id) { var post = Repository.Posts.FirstOrDefault(p => p.ID == id); if (post! = null) { post.CurrentLang = CurrentLang.ID; var postView = (PostView)ModelMapper.Map(post, typeof(Post), typeof(PostView)); return View(postView); } return RedirectToNotFoundPage; }
[HttpPost] [ValidateInput(false)] public ActionResult Edit(PostView postView) { if (ModelState.IsValid) { var post = (Post)ModelMapper.Map(postView, typeof(PostView), typeof(Post)); post.CurrentLang = CurrentLang.ID; if (post.ID == 0) { post.UserID = CurrentUser.ID; Repository.CreatePost(post); } else { Repository.UpdatePost(post); } TempData[" Message" ] = " Сохранено! "; return RedirectToAction(" Index"); } return View(postView); }
public ActionResult Delete(int id) { Repository.RemovePost(id); TempData[" Message" ] = " Удален пост";
return RedirectToAction(" Index"); } } Изменим PageableData, чтобы можно было сделать Foreach (/Models/Info/PageableData.cs): public class PageableData< T> where T: class { protected static int ItemPerPageDefault = 20;
public List< T> List { get; set; } … public PageableData(IQueryable< T> queryableSet, int page, int itemPerPage = 0) { … List = queryableSet.Skip((PageNo - 1) * itemPerPage).Take(itemPerPage) .ToList(); } } Index.cshtml (/Areas/Admin/Views/Post/Index.cshtml): @model LessonProject.Models.Info.PageableData< LessonProject.Model.Post>
@{ ViewBag.Title = " Посты"; Layout = " ~/Areas/Admin/Views/Shared/_Layout.cshtml"; }
< h2> Посты < /h2> @Html.ActionLink(" Добавить", " Create", " Post", null, new { @class = " btn" }) < table class=" table" > < thead> < tr> < th> # < /th> < th>
|