/// <summary> /// El código es el mismo de ASP.NET MVC 3, cambie el método que escribe en el response /// http://aspnet.codeplex.com/SourceControl/changeset/view/63930#266491 /// </summary> /// <param name = "context"></param> public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if (JsonRequestBehavior == JsonRequestBehavior.DenyGet && String.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException( "This request has been blocked because sensitive information could be disclosed to third party web sites when this is used in a GET request. To allow GET requests, set JsonRequestBehavior to AllowGet."); } var response = context.HttpContext.Response; if (!String.IsNullOrEmpty(ContentType)) { response.ContentType = ContentType; } else { response.ContentType = "application/json"; } if (ContentEncoding != null) { response.ContentEncoding = ContentEncoding; } if (Data != null) { var settings = new JsonSerializerSettings(); settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore; settings.Converters.Add(new IsoDateTimeConverter()); response.Write(JsonConvert.SerializeObject(this.Data, Formatting.None, settings)); } }
public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } var response = context.HttpContext.Response; response.ContentType = string.IsNullOrEmpty(ContentType) ? "application/json" : ContentType; if (ContentEncoding != null) { response.ContentEncoding = ContentEncoding; } if (Data == null) { return; } var scriptSerializer = JsonSerializer.Create(Settings); scriptSerializer.Serialize(response.Output, Data); }
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var obj = new DataTablesParam(); var request = controllerContext.HttpContext.Request.Params; obj.iDisplayStart = Convert.ToInt32(request["iDisplayStart"]); obj.iDisplayLength = Convert.ToInt32(request["iDisplayLength"]); obj.iColumns = Convert.ToInt32(request["iColumns"]); obj.sSearch = request["sSearch"]; obj.bEscapeRegex = Convert.ToBoolean(request["bEscapeRegex"]); obj.iSortingCols = Convert.ToInt32(request["iSortingCols"]); obj.sEcho = int.Parse(request["sEcho"]); for (int i = 0; i < obj.iColumns; i++) { obj.bSortable.Add(Convert.ToBoolean(request["bSortable_" + i])); obj.bSearchable.Add(Convert.ToBoolean(request["bSearchable_" + i])); obj.sSearchColumns.Add(request["sSearch_" + i]); obj.bEscapeRegexColumns.Add(Convert.ToBoolean(request["bEscapeRegex_" + i])); obj.iSortCol.Add(Convert.ToInt32(request["iSortCol_" + i])); obj.sSortDir.Add(request["sSortDir_" + i]); } return obj; }
protected override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context, IEnumerable<Attribute> attributes) { _adaptersLock.EnterReadLock(); try { List<ModelValidator> results = new List<ModelValidator>(); if (AddImplicitRequiredAttributeForValueTypes && metadata.IsRequired && !attributes.Any(a => a is RequiredAttribute)) { attributes = attributes.Concat(new[] { new RequiredAttribute() }); } foreach (ValidationAttribute attribute in attributes.OfType<ValidationAttribute>()) { DataAnnotationsModelValidationFactory factory; if (!AttributeFactories.TryGetValue(attribute.GetType(), out factory)) { factory = DefaultAttributeFactory; } results.Add(factory(metadata, context, attribute)); } return results; } finally { _adaptersLock.ExitReadLock(); } }
public override void ExecuteResult(ControllerContext context) { if (base.Content == null) { //使用IMessageHandler输出 if (_messageHandlerDocument == null) { throw new Senparc.Weixin.Exceptions.WeixinException("执行WeixinResult时提供的MessageHandler不能为Null!", null); } if (_messageHandlerDocument.FinalResponseDocument == null) { //throw new Senparc.Weixin.MP.WeixinException("FinalResponseDocument不能为Null!", null); } else { context.HttpContext.Response.ClearContent(); context.HttpContext.Response.ContentType = "text/xml"; var xml = _messageHandlerDocument.FinalResponseDocument == null ? "" : _messageHandlerDocument.FinalResponseDocument .ToString().Replace("\r\n", "\n"); //腾 using (MemoryStream ms = new MemoryStream())//迅 {//真 var bytes = Encoding.UTF8.GetBytes(xml);//的 context.HttpContext.Response.OutputStream.Write(bytes, 0, bytes.Length);//很 }//疼 } } }
public override void ExecuteResult(ControllerContext context) { ViewEngineResult result; var viewContext = InitializeView(context, out result); viewContext.View.Render(viewContext, viewContext.Writer); ReleaseView(context, result); }
public async override Task ExecuteResultAsync(ControllerContext context) { ViewEngineResult result; var viewContext = InitializeView(context, out result); await viewContext.View.RenderAsync(viewContext, viewContext.Writer).ConfigureAwait(false); ReleaseView(context, result); }
public override void ExecuteResult(ControllerContext context) { if (context == null) throw new ArgumentNullException("context"); var controllerName = context.RouteData.GetRequiredString("controller"); if (string.IsNullOrEmpty(ViewName)) { ViewName = context.RouteData.GetRequiredString("action"); } var searchedLocations = new List<string>(); var factories = ViewEngines.Engines.OfType<SparkViewFactory>(); if (!factories.Any()) throw new CompilerException("No SparkViewFactory instances are registered"); foreach (var factory in factories) { var descriptor = factory.DescriptorBuilder.BuildDescriptor( new BuildDescriptorParams("", controllerName, ViewName, MasterName, false, factory.DescriptorBuilder.GetExtraParameters(context)), searchedLocations); descriptor.Language = LanguageType.Javascript; var entry = factory.Engine.CreateEntry(descriptor); context.HttpContext.Response.ContentType = "text/javascript"; context.HttpContext.Response.Write(entry.SourceCode); return; } throw new CompilerException("Unable to find templates at " + string.Join(", ", searchedLocations.ToArray())); }
public MethodInfo FindActionMethod(ControllerContext controllerContext, string actionName) { Contract.Assert(controllerContext != null); if (controllerContext.RouteData != null) { MethodInfo target = controllerContext.RouteData.GetTargetActionMethod(); if (target != null) { // short circuit the selection process if a direct route was matched. return target; } } List<MethodInfo> finalMethods = FindActionMethods(controllerContext, actionName, AliasedMethods, NonAliasedMethods); switch (finalMethods.Count) { case 0: return null; case 1: return finalMethods[0]; default: throw CreateAmbiguousMatchException(finalMethods, actionName); } }
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException("bindingContext"); } DetectionGroup obj = null; string groupId = ModelBinderHelper.FromPostedData<String>(bindingContext, "Key"); if (string.IsNullOrEmpty(groupId)) { groupId = Guid.NewGuid().ToString("N"); obj = (DetectionGroup)(bindingContext.Model ?? new DetectionGroup(groupId, RepositoryFactory.GetRepository<IDetectionCompanyRepository, DetectionCompany>().FindBy(ModelBinderHelper.FromPostedData<String>(bindingContext, "DetectionCompany")), DetectionGroupCategory.Misc)); obj.IsLocked = false; } else { obj = RepositoryFactory.GetRepository<IDetectionGroupRepository, DetectionGroup>().FindBy(groupId); } obj.Name = ModelBinderHelper.FromPostedData<String>(bindingContext, "Name"); obj.Telephone = ModelBinderHelper.FromPostedData<String>(bindingContext, "Telephone"); return obj; }
/// <summary> /// When implemented in a class, returns client validation rules for that class. /// </summary> /// <param name="metadata">The model metadata.</param> /// <param name="context">The controller context.</param> /// <returns> /// The client validation rules for this validator. /// </returns> public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context) { var rule = new ModelClientValidationRule { ErrorMessage = ErrorMessageString ?? "Field invalid. Field can only contain alphanumeric characters: 'a-z', 'A-Z', '0-9'.", ValidationType = clientValidationRule }; rule.ValidationParameters.Add("pattern", RootModuleConstants.AlphanumericExpression); yield return rule; }
public override void ExecuteResult(ControllerContext context) { var response = context.HttpContext.Response; response.ContentType = _contentType; response.OutputStream.Write(_bytes, 0, _bytes.Length); }
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { //get the car from the session Cart cart = null; if (controllerContext.HttpContext.Session != null) { cart = (Cart)controllerContext.HttpContext.Session[sessionKey]; } //create the Cart if there wasn't one in the session data if(cart == null) { cart = new Cart(); if (controllerContext.HttpContext.Session != null) { controllerContext.HttpContext.Session[sessionKey] = cart; } } return cart; }
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { CheckPropertyFilter(bindingContext); ExtensibleModelBindingContext newBindingContext = CreateNewBindingContext(bindingContext, bindingContext.ModelName); IExtensibleModelBinder binder = Providers.GetBinder(controllerContext, newBindingContext); if (binder == null && !String.IsNullOrEmpty(bindingContext.ModelName) && bindingContext.FallbackToEmptyPrefix && bindingContext.ModelMetadata.IsComplexType) { // fallback to empty prefix? newBindingContext = CreateNewBindingContext(bindingContext, String.Empty /* modelName */); binder = Providers.GetBinder(controllerContext, newBindingContext); } if (binder != null) { bool boundSuccessfully = binder.BindModel(controllerContext, newBindingContext); if (boundSuccessfully) { // run validation and return the model newBindingContext.ValidationNode.Validate(controllerContext, null /* parentNode */); return newBindingContext.Model; } } return null; // something went wrong }
/// <summary> /// Binds the model to a value by using the specified controller context and binding context. /// </summary> /// <param name="controllerContext">The controller context.</param> /// <param name="bindingContext">The binding context.</param> /// <returns> /// The bound value. /// </returns> public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { FacebookClient client = _config.ClientProvider.CreateClient(); dynamic signedRequest = FacebookRequestHelpers.GetSignedRequest( controllerContext.HttpContext, rawSignedRequest => { return client.ParseSignedRequest(rawSignedRequest); }); if (signedRequest != null) { string accessToken = signedRequest.oauth_token; string userId = signedRequest.user_id; client.AccessToken = accessToken; return new FacebookContext { Client = client, SignedRequest = signedRequest, AccessToken = accessToken, UserId = userId, Configuration = _config }; } else { bindingContext.ModelState.AddModelError(bindingContext.ModelName, Resources.MissingSignedRequest); } return null; }
public ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache) { ControllerContext = controllerContext; PartialViewName = partialViewName; View = new TestMvcView(); return new ViewEngineResult(View, this); }
public void TryBindStrongModel_BinderExists_BinderReturnsIncorrectlyTypedObject_ReturnsTrue() { // Arrange ControllerContext controllerContext = new ControllerContext(); ExtensibleModelBindingContext bindingContext = new ExtensibleModelBindingContext() { ModelMetadata = new EmptyModelMetadataProvider().GetMetadataForType(null, typeof(int)), ModelName = "someName", ModelState = new ModelStateDictionary(), ModelBinderProviders = new ModelBinderProviderCollection(), ValueProvider = new SimpleValueProvider() }; Mock<IExtensibleModelBinder> mockIntBinder = new Mock<IExtensibleModelBinder>(); mockIntBinder .Setup(o => o.BindModel(controllerContext, It.IsAny<ExtensibleModelBindingContext>())) .Returns( delegate(ControllerContext cc, ExtensibleModelBindingContext mbc) { Assert.AreEqual("someName.key", mbc.ModelName); return true; }); bindingContext.ModelBinderProviders.RegisterBinderForType(typeof(int), mockIntBinder.Object, true /* suppressPrefixCheck */); // Act int model; bool retVal = KeyValuePairModelBinderUtil.TryBindStrongModel<int>(controllerContext, bindingContext, "key", new EmptyModelMetadataProvider(), out model); // Assert Assert.IsTrue(retVal); Assert.AreEqual(default(int), model); Assert.AreEqual(1, bindingContext.ValidationNode.ChildNodes.Count, "Child validation node should have been added."); Assert.AreEqual(0, bindingContext.ModelState.Count, "ModelState should remain unmodified."); }
private void LogRequest(ControllerContext actionContext, string context, string actName = "", string parameterList = "") { var request = actionContext.HttpContext.Request; var actionName = request.RawUrl ?? actName; try { string userName = (request.IsAuthenticated) ? actionContext.HttpContext.User.Identity.Name : request.Params["userName"]; if(string.IsNullOrEmpty(actionName)) actionName = ActionName; var sessionId = request.Params["ASP.NET_SessionId"] + "-" + userName; Task.Run( () => _logger.Log( string.Format("{0} by UserName: {1}, ActionName: {2}, Params: {3}", context, userName, actionName, parameterList), LogCategory.Verbose, sessionId)); } catch { } }
public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor) { return filterRegistry.Items.Where(item => item.IsMatching(controllerContext, actionDescriptor)) .SelectMany(item => item.BuildFilters()) .OrderBy(x => x.Order) .ToArray(); }
public void Output(ControllerContext context, object resource, string contentType) { var outerStatusCode = context.RequestContext.HttpContext.Response.StatusCode; if (!context.Controller.GetType().Name.StartsWith("Partial")) { SetContentType(context, contentType); } var result = FindView(context, resource); if (result.View != null) { context.Controller.ViewData.Model = resource; result.View.Render( new ViewContext( context, result.View, context.Controller.ViewData, new TempDataDictionary(), context.HttpContext.Response.Output ), context.HttpContext.Response.Output ); } if(result.ViewEngine != null) result.ViewEngine.ReleaseView(context, result.View); context.RequestContext.HttpContext.Response.StatusCode = outerStatusCode; }
/// <summary> /// Execute result /// </summary> /// <param name="context"></param> public override void ExecuteResult(ControllerContext context) { if (context == null) { throw new ArgumentNullException("context"); } if ((JsonRequestBehavior == JsonRequestBehavior.DenyGet) && string.Equals(context.HttpContext.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase)) { throw new InvalidOperationException("HttpMethot GET not allowed."); } var response = context.HttpContext.Response; var json = JsonConvert.SerializeObject(new { Type, Data }, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }); response.ContentType = !string.IsNullOrEmpty(ContentType) ? ContentType : "application/json"; if (ContentEncoding != null) response.ContentEncoding = ContentEncoding; if (!string.IsNullOrEmpty(context.HttpContext.Request["callback"])) { json = string.Format("{0}({1})", context.HttpContext.Request["callback"], json); } context.HttpContext.Response.Write(json); base.ExecuteResult(context); }
public override void ExecuteResult(ControllerContext controllerContext) { if (controllerContext != null) { var request = controllerContext.HttpContext.Request; object callback = request[CALLBACK_QUERYSTRING]; if (callback == null) { controllerContext.RouteData.Values.TryGetValue(CALLBACK_QUERYSTRING, out callback); } var hasCallback = !string.IsNullOrWhiteSpace(callback == null ? "" : callback as string); if (hasCallback) { SetContentTypeIfEmpty(); var response = controllerContext.HttpContext.Response; response.Write(callback); response.Write("("); base.ExecuteResult(controllerContext); response.Write(")"); } else { base.ExecuteResult(controllerContext); } } }
public bool CanFormat(ControllerContext context, object resource, string mimeType) { return ((_targetMimeType == mimeType) || string.IsNullOrEmpty(_targetMimeType) || (alsoAcceptRequestsToFormat!=null&&alsoAcceptRequestsToFormat.Contains(mimeType))) && FindView(context, resource).View != null; }
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var stringified = controllerContext.HttpContext.Request[bindingContext.ModelName]; if (string.IsNullOrEmpty(stringified)) return null; return Serializer.Deserialize(stringified, bindingContext.ModelType); }
ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache, bool partial) { if (controllerContext == null) throw new ArgumentNullException("controllerContext"); RouteData routeData = controllerContext.RouteData; string baseLocation = routeData.DataTokens[DataTokenKeys.ViewsLocation] as string; ViewEngineResult result; if (!String.IsNullOrEmpty(baseLocation)) { string controller = routeData.GetRequiredString("controller"); string location = String.Concat(baseLocation, "/", controller); routeData.Values["controller"] = location; result = (partial) ? this.wrappedEngine.FindPartialView(controllerContext, viewName, useCache) : this.wrappedEngine.FindView(controllerContext, viewName, masterName, useCache); routeData.Values["controller"] = controller; } else { result = (partial) ? this.wrappedEngine.FindPartialView(controllerContext, viewName, useCache) : this.wrappedEngine.FindView(controllerContext, viewName, masterName, useCache); } return result; }
public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (bindingContext == null) { throw new ArgumentNullException("bindingContext"); } ValueProviderResult valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); // case 1: there was no <input ... /> element containing this data if (valueResult == null) { return null; } string value = valueResult.AttemptedValue; // case 2: there was an <input ... /> element but it was left blank if (String.IsNullOrEmpty(value)) { return null; } // Future proofing. If the byte array is actually an instance of System.Data.Linq.Binary // then we need to remove these quotes put in place by the ToString() method. string realValue = value.Replace("\"", String.Empty); return Convert.FromBase64String(realValue); }
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { IPhotoService<User, PhotoAlbum, Photo, Friend> myPhotoService = new PhotoService<User, PhotoAlbum, Photo, Friend>(new FriendService<User, Friend>(new EntityHAVFriendRepository()), new EntityHAVPhotoAlbumRepository(), new EntityHAVPhotoRepository()); User myUserInfo = HAVUserInformationFactory.GetUserInformation().Details; int myUserId = Int32.Parse(BinderHelper.GetA(bindingContext, "UserId")); int myAlbumId = Int32.Parse(BinderHelper.GetA(bindingContext, "AlbumId")); string myProfilePictureURL = BinderHelper.GetA(bindingContext, "ProfilePictureURL"); string selectedProfilePictureIds = BinderHelper.GetA(bindingContext, "SelectedProfilePictureId").Trim(); IEnumerable<Photo> myPhotos = myPhotoService.GetPhotos(SocialUserModel.Create(myUserInfo), myAlbumId, myUserId); string[] splitIds = selectedProfilePictureIds.Split(','); List<int> selectedProfilePictures = new List<int>(); foreach (string id in splitIds) { if (id != string.Empty) { selectedProfilePictures.Add(Int32.Parse(id)); } } return new PhotosModel() { UserId = myUserId, ProfilePictureURL = myProfilePictureURL, Photos = myPhotos, SelectedPhotos = selectedProfilePictures }; }
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { if (controllerContext == null) { throw new ArgumentNullException("controllerContext"); } return new FormCollection(controllerContext.HttpContext.Request.Form); }
protected override void OnMetadataProcess(ModelMetadata meta, string name, ViewDataDictionary viewData, ControllerContext context) { base.OnMetadataProcess(meta, name, viewData, context); if (name.IsEmpty()) { throw new Exception("Name from ControlFor is empty"); } this.Name = name; if (meta.IsReadOnly) { this.ReadOnly = true; } if (this.FieldLabel.IsEmpty()) { this.FieldLabel = meta.GetDisplayName(); } if (this.Note.IsEmpty() && meta.Description.IsNotEmpty()) { this.Note = meta.Description; } ModelState modelState; if (viewData.ModelState.TryGetValue(name, out modelState)) { if (modelState.Errors.Count > 0) { this.CustomConfig.Add(new ConfigItem("activeError", JSON.Serialize(modelState.Errors.Select(e => e.ErrorMessage)), ParameterMode.Raw)); } } }
private static string GetResourceCommon(ControllerContext controllerContext, ModelMetadata modelMetadata, object incomingValue, Func<ControllerContext, string> resourceAccessor) { string displayName = modelMetadata.GetDisplayName(); string errorMessageTemplate = resourceAccessor(controllerContext); string errorMessage = String.Format(CultureInfo.CurrentCulture, errorMessageTemplate, incomingValue, displayName); return errorMessage; }
} // End of the UnprotectCookieValue method /// <summary> /// Get a 404 not found page /// </summary> /// <returns>A string with html</returns> public static string GetHttpNotFoundPage() { // Create the string to return string htmlString = ""; // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); // Get the error page StaticPage staticPage = StaticPage.GetOneByConnectionId(5, currentDomain.front_end_language); staticPage = staticPage != null ? staticPage : new StaticPage(); // Get the translated texts KeyStringList tt = StaticText.GetAll(currentDomain.front_end_language, "id", "ASC"); // Create the Route data System.Web.Routing.RouteData routeData = new System.Web.Routing.RouteData(); routeData.Values.Add("controller", "home"); // Create the controller context System.Web.Mvc.ControllerContext context = new System.Web.Mvc.ControllerContext(new System.Web.Routing.RequestContext(new HttpContextWrapper(HttpContext.Current), routeData), new Annytab.Webshop.Controllers.homeController()); // Create the bread crumb list List<BreadCrumb> breadCrumbs = new List<BreadCrumb>(2); breadCrumbs.Add(new BreadCrumb(tt.Get("start_page"), "/")); breadCrumbs.Add(new BreadCrumb(staticPage.link_name, "/home/error/404")); // Set form values context.Controller.ViewBag.BreadCrumbs = breadCrumbs; context.Controller.ViewBag.CurrentCategory = new Category(); context.Controller.ViewBag.TranslatedTexts = tt; context.Controller.ViewBag.CurrentDomain = currentDomain; context.Controller.ViewBag.CurrentLanguage = Language.GetOneById(currentDomain.front_end_language); context.Controller.ViewBag.StaticPage = staticPage; context.Controller.ViewBag.PricesIncludesVat = HttpContext.Current.Session["PricesIncludesVat"] != null ? Convert.ToBoolean(HttpContext.Current.Session["PricesIncludesVat"]) : currentDomain.prices_includes_vat; // Render the view using (StringWriter stringWriter = new StringWriter(new StringBuilder(), CultureInfo.InvariantCulture)) { string viewPath = currentDomain.custom_theme_id == 0 ? "/Views/home/error.cshtml" : "/Views/theme/error.cshtml"; System.Web.Mvc.RazorView razor = new System.Web.Mvc.RazorView(context, viewPath, null, false, null); razor.Render(new System.Web.Mvc.ViewContext(context, razor, context.Controller.ViewData, context.Controller.TempData, stringWriter), stringWriter); htmlString += stringWriter.ToString(); } //// Create the web page //notFoundString += "<html><head>"; //notFoundString += "<meta charset=\"utf-8\">"; //notFoundString += "<title>" + staticPage.title + "</title></head>"; //notFoundString += "<body><div style=\"text-align:center;margin:200px auto auto auto;\"><h1>" + staticPage.title + "</h1>"; //notFoundString += "<p>" + staticPage.main_content + "</p>"; //notFoundString += "<a href=\"/\">" + tt.Get("start_page") + "</a></div></body>"; //notFoundString += "</html>"; // Return the string return htmlString; } // End of the GetHttpNotFoundPage method
} // End of the UnprotectCookieValue method /// <summary> /// Get a 404 not found page /// </summary> /// <returns>A string with html</returns> public static string GetHttpNotFoundPage() { // Create the string to return string htmlString = ""; // Get the current domain Domain currentDomain = Tools.GetCurrentDomain(); // Get the error page StaticPage staticPage = StaticPage.GetOneByConnectionId(4, currentDomain.front_end_language); staticPage = staticPage != null ? staticPage : new StaticPage(); // Get the translated texts KeyStringList tt = StaticText.GetAll(currentDomain.front_end_language, "id", "ASC"); // Create the Route data System.Web.Routing.RouteData routeData = new System.Web.Routing.RouteData(); routeData.Values.Add("controller", "home"); // Create the controller context System.Web.Mvc.ControllerContext context = new System.Web.Mvc.ControllerContext(new System.Web.Routing.RequestContext(new HttpContextWrapper(HttpContext.Current), routeData), new Annytab.Blogsite.Controllers.homeController()); // Create the bread crumb list List<BreadCrumb> breadCrumbs = new List<BreadCrumb>(2); breadCrumbs.Add(new BreadCrumb(tt.Get("start_page"), "/")); breadCrumbs.Add(new BreadCrumb(staticPage.link_name, "/home/error/404")); // Set form values context.Controller.ViewBag.BreadCrumbs = breadCrumbs; context.Controller.ViewBag.CurrentCategory = new Category(); context.Controller.ViewBag.TranslatedTexts = tt; context.Controller.ViewBag.CurrentDomain = currentDomain; context.Controller.ViewBag.CurrentLanguage = Language.GetOneById(currentDomain.front_end_language); context.Controller.ViewBag.StaticPage = staticPage; // Render the view using (StringWriter stringWriter = new StringWriter(new StringBuilder(), CultureInfo.InvariantCulture)) { string viewPath = currentDomain.custom_theme_id == 0 ? "/Views/home/error.cshtml" : "/Views/theme/error.cshtml"; System.Web.Mvc.RazorView razor = new System.Web.Mvc.RazorView(context, viewPath, null, false, null); razor.Render(new System.Web.Mvc.ViewContext(context, razor, context.Controller.ViewData, context.Controller.TempData, stringWriter), stringWriter); htmlString += stringWriter.ToString(); } // Return the string return htmlString; } // End of the GetHttpNotFoundPage method
protected override System.Web.Mvc.ViewEngineResult FindView(System.Web.Mvc.ControllerContext context) { return(default(System.Web.Mvc.ViewEngineResult)); }
public override void ExecuteResult(System.Web.Mvc.ControllerContext context) { }
internal object BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { object model = bindingContext.Model; Type modelType = bindingContext.ModelType; // if we're being asked to create an array, create a list instead, then coerce to an array after the list is created if (model == null && modelType.IsArray) { Type elementType = modelType.GetElementType(); Type listType = typeof(List <>).MakeGenericType(elementType); object collection = CreateModel(controllerContext, bindingContext, listType); ModelBindingContext arrayBindingContext = new ModelBindingContext() { ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => collection, listType), ModelName = bindingContext.ModelName, ModelState = bindingContext.ModelState, PropertyFilter = bindingContext.PropertyFilter, ValueProvider = bindingContext.ValueProvider }; IList list = (IList)UpdateCollection(controllerContext, arrayBindingContext, elementType); if (list == null) { return(null); } Array array = Array.CreateInstance(elementType, list.Count); list.CopyTo(array, 0); return(array); } if (model == null) { model = CreateModel(controllerContext, bindingContext, modelType); } // special-case IDictionary<,> and ICollection<> Type dictionaryType = TypeHelpers.ExtractGenericInterface(modelType, typeof(IDictionary <,>)); if (dictionaryType != null) { Type[] genericArguments = dictionaryType.GetGenericArguments(); Type keyType = genericArguments[0]; Type valueType = genericArguments[1]; ModelBindingContext dictionaryBindingContext = new ModelBindingContext() { ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, modelType), ModelName = bindingContext.ModelName, ModelState = bindingContext.ModelState, PropertyFilter = bindingContext.PropertyFilter, ValueProvider = bindingContext.ValueProvider }; object dictionary = UpdateDictionary(controllerContext, dictionaryBindingContext, keyType, valueType); return(dictionary); } Type enumerableType = TypeHelpers.ExtractGenericInterface(modelType, typeof(IEnumerable <>)); if (enumerableType != null) { Type elementType = enumerableType.GetGenericArguments()[0]; Type collectionType = typeof(ICollection <>).MakeGenericType(elementType); if (collectionType.IsInstanceOfType(model)) { ModelBindingContext collectionBindingContext = new ModelBindingContext() { ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(() => model, modelType), ModelName = bindingContext.ModelName, ModelState = bindingContext.ModelState, PropertyFilter = bindingContext.PropertyFilter, ValueProvider = bindingContext.ValueProvider }; object collection = UpdateCollection(controllerContext, collectionBindingContext, elementType); return(collection); } } // otherwise, just update the properties on the complex type BindComplexElementalModel(controllerContext, bindingContext, model); return(model); }
internal object UpdateDictionary(ControllerContext controllerContext, ModelBindingContext bindingContext, Type keyType, Type valueType) { bool stopOnIndexNotFound; IEnumerable <string> indexes; GetIndexes(bindingContext, out stopOnIndexNotFound, out indexes); IModelBinder keyBinder = Binders.GetBinder(keyType); IModelBinder valueBinder = Binders.GetBinder(valueType); // build up a list of items from the request List <KeyValuePair <object, object> > modelList = new List <KeyValuePair <object, object> >(); foreach (string currentIndex in indexes) { string subIndexKey = CreateSubIndexName(bindingContext.ModelName, currentIndex); string keyFieldKey = CreateSubPropertyName(subIndexKey, "key"); string valueFieldKey = CreateSubPropertyName(subIndexKey, "value"); if (!(bindingContext.ValueProvider.ContainsPrefix(keyFieldKey) && bindingContext.ValueProvider.ContainsPrefix(valueFieldKey))) { if (stopOnIndexNotFound) { // we ran out of elements to pull break; } else { continue; } } // bind the key ModelBindingContext keyBindingContext = new ModelBindingContext() { ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, keyType), ModelName = keyFieldKey, ModelState = bindingContext.ModelState, ValueProvider = bindingContext.ValueProvider }; object thisKey = keyBinder.BindModel(controllerContext, keyBindingContext); // we need to merge model errors up AddValueRequiredMessageToModelState(controllerContext, bindingContext.ModelState, keyFieldKey, keyType, thisKey); if (!keyType.IsInstanceOfType(thisKey)) { // we can't add an invalid key, so just move on continue; } // bind the value modelList.Add(CreateEntryForModel(controllerContext, bindingContext, valueType, valueBinder, valueFieldKey, thisKey)); } // Let's try another method if (modelList.Count == 0) { IEnumerableValueProvider enumerableValueProvider = bindingContext.ValueProvider as IEnumerableValueProvider; if (enumerableValueProvider != null) { IDictionary <string, string> keys = enumerableValueProvider.GetKeysFromPrefix(bindingContext.ModelName); foreach (var thisKey in keys) { modelList.Add(CreateEntryForModel(controllerContext, bindingContext, valueType, valueBinder, thisKey.Value, thisKey.Key)); } } } // replace the original collection object dictionary = bindingContext.Model; CollectionHelpers.ReplaceDictionary(keyType, valueType, dictionary, modelList); return(dictionary); }
protected virtual void OnPropertyValidated(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value) { // default implementation does nothing }
protected virtual bool OnPropertyValidating(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value) { // default implementation does nothing return(true); }
private static string GetValueRequiredResource(ControllerContext controllerContext) { return(GetUserResourceString(controllerContext, "PropertyValueRequired") ?? MvcResources.DefaultModelBinder_ValueRequired); }
protected virtual bool OnModelUpdating(ControllerContext controllerContext, ModelBindingContext bindingContext) { // default implementation does nothing return(true); }
protected virtual PropertyDescriptorCollection GetModelProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) { return(GetTypeDescriptor(controllerContext, bindingContext).GetProperties()); }
protected virtual ICustomTypeDescriptor GetTypeDescriptor(ControllerContext controllerContext, ModelBindingContext bindingContext) { return(TypeDescriptorHelper.Get(bindingContext.ModelType)); }
internal object UpdateDictionary(ControllerContext controllerContext, ModelBindingContext bindingContext, Type keyType, Type valueType) { IModelBinder keyBinder = Binders.GetBinder(keyType); IModelBinder valueBinder = Binders.GetBinder(valueType); // build up a list of items from the request List <KeyValuePair <object, object> > modelList = new List <KeyValuePair <object, object> >(); for (int currentIndex = 0; ; currentIndex++) { string subIndexKey = CreateSubIndexName(bindingContext.ModelName, currentIndex); string keyFieldKey = CreateSubPropertyName(subIndexKey, "key"); string valueFieldKey = CreateSubPropertyName(subIndexKey, "value"); if (!(DictionaryHelpers.DoesAnyKeyHavePrefix(bindingContext.ValueProvider, keyFieldKey) && DictionaryHelpers.DoesAnyKeyHavePrefix(bindingContext.ValueProvider, valueFieldKey))) { // we ran out of elements to pull break; } // bind the key ModelBindingContext keyBindingContext = new ModelBindingContext() { ModelName = keyFieldKey, ModelState = bindingContext.ModelState, ModelType = keyType, ValueProvider = bindingContext.ValueProvider }; object thisKey = keyBinder.BindModel(controllerContext, keyBindingContext); // we need to merge model errors up VerifyValueUsability(controllerContext, bindingContext.ModelState, keyFieldKey, keyType, thisKey); if (!keyType.IsInstanceOfType(thisKey)) { // we can't add an invalid key, so just move on continue; } // bind the value ModelBindingContext valueBindingContext = new ModelBindingContext() { ModelName = valueFieldKey, ModelState = bindingContext.ModelState, ModelType = valueType, PropertyFilter = bindingContext.PropertyFilter, ValueProvider = bindingContext.ValueProvider }; object thisValue = valueBinder.BindModel(controllerContext, valueBindingContext); // we need to merge model errors up VerifyValueUsability(controllerContext, bindingContext.ModelState, valueFieldKey, valueType, thisValue); KeyValuePair <object, object> kvp = new KeyValuePair <object, object>(thisKey, thisValue); modelList.Add(kvp); } // if there weren't any elements at all in the request, just return if (modelList.Count == 0) { return(null); } // replace the original collection object dictionary = bindingContext.Model; CollectionHelpers.ReplaceDictionary(keyType, valueType, dictionary, modelList); return(dictionary); }
public static string RenderPartialViewToString(nameFile.ControllerContext controllerContext, object model) { return(RenderPartialViewToString(controllerContext, null, model)); }
protected override bool GetIsVisible(MenuItem menuItem, System.Web.Mvc.ControllerContext controllerContext) { return(Repository.Current.EnableBroadcasting); }
public static string RenderPartialViewToString(nameFile.ControllerContext controllerContext, string viewName) { return(RenderPartialViewToString(controllerContext, viewName, null)); }
public IEnumerable <ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context) { return(CombinedItems.SelectMany(provider => provider.GetValidators(metadata, context))); }
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo) { return(String.Equals(actionName, Name, StringComparison.OrdinalIgnoreCase)); }