public override void OnActionExecuted(ActionExecutedContext filterContext) { string hint = filterContext.RequestContext.HttpContext.Request.Params["ViewHint"]; if (hint == null) { hint = filterContext.RequestContext.RouteData.Values["ViewHint"] as string; } if (!string.IsNullOrWhiteSpace(hint) && hint.Length <= 100 && new Regex(@"^\w+$").IsMatch(hint)) { ViewResultBase res = filterContext.Result as ViewResultBase; if (res != null) { if (hint == "json") { JsonResult jr = new JsonResult(); jr.Data = res.ViewData.Model; jr.JsonRequestBehavior = jsBehavior; filterContext.Result = jr; } else { res.ViewName = hint; } } } base.OnActionExecuted(filterContext); }
public virtual bool TryGetResult(ViewResultBase viewResult, ContentType responseFormat, out MultiFormatActionResult actionResult) { if (FormatManager.Current.CanSerialize(responseFormat)) { if (viewResult.ViewData.Model == null) { throw new HttpException((int)this.StatusOnNullModel, this.StatusOnNullModel.ToString()); } actionResult = new MultiFormatActionResult(viewResult.ViewData.Model, responseFormat); return(true); } switch (responseFormat.MediaType) { case "application/octet-stream": case "application/x-www-form-urlencoded": case "text/html": case "*/*": actionResult = null; return(true); default: actionResult = null; return(false); } }
public void Transfer_Money_Shows_A_List_Of_Bank_Accounts() { /* * Arrange * 1º - Create a dummy list of transfers * 2º - Initialize stub of IBankingManagementService * 3º - Create controller to test */ IList <BankAccount> accounts = GetFakeBankAccounts(); SIBankingManagementService bankingService = new SIBankingManagementService(); bankingService.FindPagedBankAccountsInt32Int32 = (page, pageSize) => accounts.Skip(page * pageSize).Take(pageSize).ToList(); BankAccountController controller = new BankAccountController(bankingService); //Act ViewResultBase result = controller.TransferMoney() as ViewResult; //Assert Assert.IsNotNull(result); BankAccountListViewModel model = result.ViewData.Model as BankAccountListViewModel; Assert.IsNotNull(model); }
public AutoMapViewResult(Type sourceType, Type destinationType, object domainModel, ViewResultBase view) { SourceType = sourceType; DestinationType = destinationType; DomainModel = domainModel; View = view; }
private static void AssertResult(ViewResultBase result, IEnumerable <Campaign> campaigns, int?page) { Assert.IsNotNull(result); Assert.AreEqual("Index", result.ViewName); var model = result.ViewData.Model as PaginatedList <CampaignRecord>; Assert.IsNotNull(model); // Only the campaigns for this page are needed. page = page ?? 1; var expectedCampaigns = campaigns.Skip((page.Value - 1) * MaxCampaignsPerPage).Take(MaxCampaignsPerPage); Assert.AreEqual(campaigns.Count(), model.TotalItems); Assert.AreEqual(expectedCampaigns.Count(), model.CurrentItems.Count()); for (var index = 0; index < expectedCampaigns.Count(); ++index) { Assert.AreEqual(expectedCampaigns.ElementAt(index).Name, model.CurrentItems.ElementAt(index).Name); } // Make sure the others are not there. var notExpectedCampaigns = campaigns.Take((page.Value - 1) * MaxCampaignsPerPage).Concat(campaigns.Skip(page.Value * MaxCampaignsPerPage)); foreach (var notExpectedCampaign in notExpectedCampaigns) { var notExpectedCampaignName = notExpectedCampaign.Name; Assert.IsFalse(model.CurrentItems.Any(c => c.Name == notExpectedCampaignName)); } }
public static ViewResultBase ItemNotFound(Controller trigger, String message) { LogManager.GetLogger(trigger.GetType()).Warn("Item Not Found! Message = {0}", message); ErrorViewModel viewmodel = new ErrorViewModel(); viewmodel.ErrorText = message; viewmodel.ErrorRequestPath = trigger.HttpContext.Request.Url.AbsoluteUri; if (trigger.Request.UrlReferrer != null) { viewmodel.ReturnUrl = trigger.Request.UrlReferrer.AbsoluteUri; } ViewDataDictionary viewData = new ViewDataDictionary { Model = viewmodel }; ViewResultBase viewresult = trigger.Request.IsAjaxRequest() ? (ViewResultBase) new PartialViewResult() : (ViewResultBase) new ViewResult(); viewresult.ViewName = "ItemNotFound"; viewresult.ViewData = viewData; return(viewresult); }
public void OnResultExecuting(ResultExecutingContext filterContext) { if (!filterContext.IsChildAction && isMvcViewResult(filterContext)) { ViewResultBase viewResult = (ViewResultBase)filterContext.Result; if (viewResult != null) { var viewName = filterContext.RouteData.GetRequiredString("action");; var viewEngineResult = viewResult.ViewEngineCollection.FindView(filterContext.Controller.ControllerContext, viewName, null); if (viewEngineResult != null && viewEngineResult.View != null) { var viewPath = VirtualPathUtility.ToAbsolute(((RazorView)viewEngineResult.View).ViewPath); viewPath = viewPath.LastIndexOf(".cshtml") > 0 ? viewPath.Substring(0, viewPath.LastIndexOf(".cshtml")) : viewPath; filterContext.Controller.ViewBag.subPageVirtualPath = viewPath; var jsPath = viewPath + ".js"; if (pathProvider.FileExists(jsPath)) { filterContext.Controller.ViewBag.subPageJsVirtualPath = jsPath; } var cssPath = viewPath + ".css"; if (pathProvider.FileExists(cssPath)) { filterContext.Controller.ViewBag.subPageCssVirtualPath = cssPath; } var extension = extensionManager.GetExtension(filterContext.Controller.GetType().Assembly.GetName().Name); filterContext.Controller.ViewBag.extensionName = extension?.Name; } } } }
public static TViewModel AssertGetViewModel <TViewModel>(this ViewResultBase result) { Assert.IsNotNull(result, "View result is null."); Assert.IsNotNull(result.Model, "View result's model is null."); Assert.IsInstanceOfType(result.Model, typeof(TViewModel), "View result's model is not of the expected type."); return((TViewModel)result.Model); }
public void Index_Returns_A_Paged_List_Of_Customers() { /* * Arrange * 1º - Create a dummy list of customers * 2º - Initialize stub of SICustomerManagementService * 3º - Create controller to test */ IList <Customer> customers = GetFakeCustomers(); SICustomerManagementService customerService = new SICustomerManagementService(); customerService.FindPagedCustomersInt32Int32 = (page, pageSize) => customers.Skip(page * pageSize).Take(pageSize).ToList(); CustomerController controller = new CustomerController(customerService); //Act ViewResultBase result = controller.Index(0, 5) as ViewResult; //Assert Assert.IsNotNull(result, "Expected a view"); CustomerListViewModel model = result.ViewData.Model as CustomerListViewModel; Assert.IsNotNull(model, "model is null or different than CustomerListViewModel"); IList <Customer> resultCustomers = (model.PageItems as IEnumerable <Customer>).ToList(); Assert.AreEqual(5, resultCustomers.Count(), "Expected a different number of customers"); }
private static void AssertEditViewIsCorrectlyCalled(ViewResultBase result) { Assert.AreEqual("Edit", result.ViewName); var viewData = result.ViewData.Model as ProductViewData; Assert.IsNotNull(viewData, "viewData is not ShopViewData"); }
public async void GetSubmit_HappyPath_ReturnsSubmitViewWithPopulatedViewModel() { // Arrange DataReturnForSubmission dataReturnForSubmission = new DataReturnForSubmission( new Guid("06FFB265-46D3-4CE3-805A-A81F1B11622A"), new Guid("AA7DA88A-19AF-4130-A24D-45389D97B274"), 2015, QuarterType.Q4, A.Dummy <IReadOnlyCollection <DataReturnWarning> >(), A.Dummy <IReadOnlyCollection <DataReturnError> >(), false); A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <FetchDataReturnForSubmission> ._)) .WhenArgumentsMatch(args => args.Get <FetchDataReturnForSubmission>("request").DataReturnUploadId == new Guid("06FFB265-46D3-4CE3-805A-A81F1B11622A")) .Returns(dataReturnForSubmission); DataReturnsController controller = GetDummyDataReturnsController(weeeClient); // Act ActionResult result = await controller.Submit( new Guid("AA7DA88A-19AF-4130-A24D-45389D97B274"), new Guid("06FFB265-46D3-4CE3-805A-A81F1B11622A")); // Assert Assert.IsAssignableFrom <ViewResultBase>(result); ViewResultBase viewResult = result as ViewResultBase; Assert.True(viewResult.ViewName == string.Empty || viewResult.ViewName == "Submit", "The GET Submit action must return the view called \"Submit\"."); Assert.IsAssignableFrom <SubmitViewModel>(viewResult.Model); SubmitViewModel viewModel = viewResult.Model as SubmitViewModel; Assert.Equal(dataReturnForSubmission, viewModel.DataReturn); }
public override void OnActionExecuted(ActionExecutedContext filterContext) { object model; ViewResultBase result = filterContext.Result as ViewResultBase; if (result != null) { model = result.Model; } else { JsonResult jsonResult = filterContext.Result as JsonResult; if (jsonResult == null) { return; } model = jsonResult.Data; } if (model == null) { return; } PageVm pageVm = model as PageVm; if (pageVm == null) { FormatterResolver.ApplyFormatting <EntityLocation>(model, EntityLocation.Search); return; } FormatterResolver.ApplyFormatting <PageType>(model, pageVm.PageType); }
public GridViewResultAdapter(ViewResultBase viewResult) { var viewData = viewResult.ViewData; modelState = viewData.ModelState; model = viewData.Model as IGridModel ?? new GridModel(); }
public static TViewModel AssertGetViewModel <TViewModel>(this ViewResultBase result, TViewModel expectedModel) { TViewModel actualModel = AssertGetViewModel <TViewModel>(result); Assert.AreEqual(expectedModel, actualModel, "View's model is different than expected."); return(actualModel); }
public void WidgetController_EditGet_ShouldReturnThePassedWidget() { var textWidget = new TextWidget {Site = new Site()}; ViewResultBase result = _widgetController.Edit_Get(textWidget); result.Model.Should().Be(textWidget); }
private void SetMenu(ResultExecutingContext filterContext, ViewResultBase viewResult) { var menu = Menu.Begin(); menu.SetListClass("sf-menu"); _Services.ForEach(service => menu.Add(BuildSection(service))); menu.Prepare(filterContext.Controller.ControllerContext); viewResult.ViewData[MenuKey] = menu.RenderHtml(); }
private static ITask CheckTask(ViewResultBase taskData) { Assert.IsInstanceOfType(taskData.ViewData.Model, typeof(ITask)); ITask task = taskData.ViewData.Model as ITask; Assert.IsNotNull(task); Assert.AreNotEqual(task.Id, 0); return(task); }
private void FixupViewResult(ViewResultBase result, ControllerContext context) { if (result == null) { return; } result.ViewData = context.Controller.ViewData; result.TempData = context.Controller.TempData; }
private static string GetViewName(ActionExecutedContext filterContext, ViewResultBase viewResultBase) { var viewName = viewResultBase.ViewName; if (string.IsNullOrEmpty(viewName)) { viewName = filterContext.RouteData.GetRequiredString("action"); } return(viewName); }
// fixme - copied from Umbraco.Web.Mvc.ControllerExtensions static void EnsureViewObjectDataOnResult(ControllerBase controller, ViewResultBase result) { //when merging we'll create a new dictionary, otherwise you might run into an enumeration error // caused from ModelStateDictionary result.ViewData.ModelState.Merge(new ModelStateDictionary(controller.ViewData.ModelState)); // Temporarily copy the dictionary to avoid enumerator-modification errors var newViewDataDict = new ViewDataDictionary(controller.ViewData); foreach (var d in newViewDataDict) { result.ViewData[d.Key] = d.Value; } result.TempData = controller.TempData; if (result.View != null) { return; } if (string.IsNullOrEmpty(result.ViewName)) { result.ViewName = controller.ControllerContext.RouteData.GetRequiredString("action"); } if (result.View != null) { return; } if (result is PartialViewResult) { var viewEngineResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, result.ViewName); if (viewEngineResult.View == null) { throw new InvalidOperationException("Could not find the view " + result.ViewName + ", the following locations were searched: " + Environment.NewLine + string.Join(Environment.NewLine, viewEngineResult.SearchedLocations)); } result.View = viewEngineResult.View; } else if (result is ViewResult) { var vr = (ViewResult)result; var viewEngineResult = ViewEngines.Engines.FindView(controller.ControllerContext, vr.ViewName, vr.MasterName); if (viewEngineResult.View == null) { throw new InvalidOperationException("Could not find the view " + vr.ViewName + ", the following locations were searched: " + Environment.NewLine + string.Join(Environment.NewLine, viewEngineResult.SearchedLocations)); } result.View = viewEngineResult.View; } }
/// <summary> /// Adds errors from <paramref name="result"/> to <see cref="ViewDataDictionary.ModelState"/> in /// <paramref name="viewResult"/> and sets status and header information to the current HTTP response. /// </summary> /// <param name="viewResult">The <see cref="ViewResultBase"/> instance.</param> /// <param name="result">The <see cref="Result"/> instance.</param> /// <returns> /// A new <see cref="ActionResult"/> object that wraps <paramref name="viewResult"/> and adds status and header /// information to the current HTTP response, when executed. /// </returns> /// <example> /// This extension method is usually used like this: /// <code> /// if (result.IsError) { /// return View().WithErrors(result); /// } /// </code> /// </example> public static ActionResult WithErrors(this ViewResultBase viewResult, Result result) { if (viewResult == null) { throw new ArgumentNullException("viewResult"); } AddModelErrors(viewResult.ViewData.ModelState, result); return(new ActionResultWrapper(viewResult, result)); }
private static void AssertUserEditViewDataIsCorrect(ViewResultBase result) { var viewData = result.ViewData.Model as ShopViewData; Assert.IsNotNull(viewData, "ViewData is not ShopViewData"); // there should be some roles Assert.IsNotNull(viewData.Roles, "viewData.Roles is null"); // add should have inserted a default user into the viewData Assert.IsNotNull(viewData.User, "viewData User is null"); }
// // GET: /Base/ //public ActionResult Index() //{ // return View(); //} protected override void OnActionExecuted(ActionExecutedContext filterContext) { //is it a view? ViewResultBase view = filterContext.Result as ViewResultBase; if (view == null) { return; //niks te doen :) } //use culture-specific view (not implemented in this case) base.OnActionExecuted(filterContext); }
public static ViewResultBase WithData(this ViewResultBase viewResultBase, Type entityType, object data) { if (viewResultBase.ViewData.ContainsKey(entityType.ToString())) { viewResultBase.ViewData[entityType.ToString()] = data; } else { viewResultBase.ViewData.Add(entityType.ToString(), data); } return(viewResultBase); }
protected override void OnActionExecuted(ActionExecutedContext filterContext) { // Is it View ? ViewResultBase view = filterContext.Result as ViewResultBase; if (view == null) { // if not exit return; } var cultureName = Thread.CurrentThread.CurrentCulture.Name; // e.g. "en-US" // filterContext.HttpContext.Request.UserLanguages[0]; // needs validation return "en-us" as default // Is it default culture? exit if (cultureName == CultureHelper.GetDefaultCulture()) { return; } // Are views implemented separately for this culture? if not exit var viewImplemented = CultureHelper.IsViewSeparate(cultureName); if (viewImplemented == false) { return; } var viewName = view.ViewName; int i; if (string.IsNullOrEmpty(viewName)) { viewName = filterContext.RouteData.Values["action"] + "." + cultureName; // Index.en-US} } else if ((i = viewName.IndexOf('.')) > 0) { // contains . like "Index.cshtml" viewName = viewName.Substring(0, i + 1) + cultureName + viewName.Substring(i); } else { viewName += "." + cultureName; // e.g. "Index" ==> "Index.en-Us" } view.ViewName = viewName; filterContext.Controller.ViewBag._culture = "." + cultureName; base.OnActionExecuted(filterContext); }
public string RenderActionResultToString(ViewResultBase viewResultToRender) { var viewEngineResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewResultToRender.ViewName); var view = viewEngineResult.View; using (var sw = new StringWriter()) { var viewContext = new ViewContext(ControllerContext, view, viewResultToRender.ViewData, viewResultToRender.TempData, sw); view.Render(viewContext, sw); viewEngineResult.ViewEngine.ReleaseView(ControllerContext, view); return(sw.ToString()); } }
protected override void OnActionExecuted(ActionExecutedContext filterContext) { base.OnActionExecuted(filterContext); ViewResultBase result = filterContext.Result as ViewResultBase; if (result != null) { SettingsViewModel model = result.Model as SettingsViewModel; if (model != null) { model.EnableLog = Properties.Settings.Default.EnableClientLogging; } } }
public override void OnActionExecuted(ActionExecutedContext filterContext) { ViewResultBase view = filterContext.Result as ViewResultBase; if (view != null) { string viewName = view.ViewName; // If we did not explicitly specify the view name in View() method, // it will be same as the action name. So let's get that. if (String.IsNullOrEmpty(viewName)) { viewName = filterContext.ActionDescriptor.ActionName; } view.ViewBag.CurrentView = viewName.ToTitleCase(); } }
public static ViewResultBase WithData <TDataType>(this ViewResultBase viewResultBase, TDataType data) { if (Equals(data, default(TDataType))) { return(viewResultBase); } if (viewResultBase.ViewData.ContainsKey(typeof(TDataType).ToString())) { viewResultBase.ViewData[typeof(TDataType).ToString()] = data; } else { viewResultBase.ViewData.Add(typeof(TDataType).ToString(), data); } return(viewResultBase); }
public async void GetIndex_WithInactiveAndRejectedAssociation_ShowsOnlyInactiveAssociation() { // Arrange IWeeeClient weeeClient = A.Fake <IWeeeClient>(); A.CallTo(() => weeeClient.SendAsync(A <string> ._, A <GetUserOrganisationsByStatus> ._)) .Returns(new List <OrganisationUserData> { new OrganisationUserData { OrganisationId = new Guid("EF4B78BA-3D73-4B99-A996-714677590A78"), UserStatus = UserStatus.Inactive, Organisation = new OrganisationData { OrganisationName = "Organisation Name 1", OrganisationStatus = OrganisationStatus.Complete, } }, new OrganisationUserData { OrganisationId = new Guid("EF4B78BA-3D73-4B99-A996-714677590A78"), UserStatus = UserStatus.Rejected, Organisation = new OrganisationData { OrganisationName = "Organisation Name 1", OrganisationStatus = OrganisationStatus.Complete, } } }); OrganisationController controller = new OrganisationController(() => weeeClient); // Act ActionResult result = await controller.Index(); // Assert Assert.IsAssignableFrom <ViewResultBase>(result); ViewResultBase viewResult = result as ViewResultBase; Assert.IsAssignableFrom <PendingOrganisationsViewModel>(viewResult.Model); PendingOrganisationsViewModel model = viewResult.Model as PendingOrganisationsViewModel; Assert.Equal(1, model.InaccessibleOrganisations.Count()); OrganisationUserData result1 = model.InaccessibleOrganisations.First(); Assert.Equal(UserStatus.Inactive, result1.UserStatus); }