public void IndexSinPermiso() { //Nos aseguramos que admin no haya quedado logeado por otros tests. CurrentUser.deleteCurrentUser("*****@*****.**"); CurrentUser.setCurrentUser("*****@*****.**", "Estudiante", "0000000001", "0000000001"); var httpContext = new HttpContext( new HttpRequest("", "http://*****:*****@mail.com"); }
private static Dictionary<string, string> DictionaryFromObject(object htmlAttributes) { var routes = new System.Web.Routing.RouteValueDictionary(htmlAttributes); var dict = new Dictionary<string, string>(); foreach (var kvp in routes) dict.Add(kvp.Key, kvp.Value.ToString()); return dict; }
public string GetAppName() { System.Web.Routing.RouteValueDictionary routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values; string name = string.Empty; if (routeValues != null) { if (routeValues.ContainsKey("action")) { name += routeValues["action"].ToString(); } if (routeValues.ContainsKey("controller")) { name += routeValues["controller"].ToString(); } } if (name == string.Empty) { return("app"); } return(name.FirstCharToLower()); }
void redirectToUnauthorize(ActionExecutingContext filterContext, string actionName, string controllerName) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("action", actionName); route.Add("controller", controllerName); filterContext.Result = new RedirectToRouteResult(route); }
protected override void OnException(ExceptionContext filterContext) { //Si la petición es del tipo AJAX se devuelve un JSON y STATUS 500 if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest") { //Return JSON filterContext.Result = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet, Data = new { error = true, message = "Exception:" + filterContext.Exception.Message, stack = "StackTrace:" + filterContext.Exception.StackTrace.ToString() } }; filterContext.HttpContext.Response.Status = "500"; } else { //Redirigimos a la pagina de error string actionName = this.ControllerContext.RouteData.Values["action"].ToString(); string controllerName = this.ControllerContext.RouteData.Values["controller"].ToString(); System.Web.Routing.RouteValueDictionary values = new System.Web.Routing.RouteValueDictionary(); values.Add("msg", filterContext.Exception.Message); values.Add("controllerOriginal", controllerName); values.Add("ActionOriginal", actionName); filterContext.ExceptionHandled = true; filterContext.Result = this.RedirectToAction("ExceptionError", "Error", values); } base.OnException(filterContext); }
public PageMenuItem(Page page) { base.Action = "Index"; base.Controller = "Page"; base.Area = "Sites"; base.Text = page.Name; if (page.Navigation != null && !string.IsNullOrEmpty(page.Navigation.DisplayText)) { base.Text = page.Navigation.DisplayText; } base.Tips = page.Name; base.Visible = true; RouteValues = new System.Web.Routing.RouteValueDictionary(); RouteValues.Add("parentPage", page.FullName); HtmlAttributes = new System.Web.Routing.RouteValueDictionary(); if (page.IsDefault) { HtmlAttributes.Add("class", "home"); } //this.Page = page; Initializer = new PageMenuItemInitializer(); }
//[HttpPost] //FormCollection f -> f["username"]; //Request["username"] public ActionResult Check() { string name = Request["username"]; string pass = Request["userpass"]; if (name == "" || pass == "") { ViewBag.errors = "请输入用户名和密码!"; return View("index"); } ViewBag.username = name; ViewBag.userpass = pass; //检测 string rs = checkLogin(name, pass); if (rs == "succ"){ //转到登录前页面 //TODO: 应该带上参数ROUTERDATA //string controller = Session["lastController"] != null ? Session["lastController"].ToString() : ""; //string action = Session["lastAction"] != null ? Session["lastAction"].ToString() : ""; //Session["lastController"] = null; //Session["lastAction"] = null; System.Web.Routing.RouteValueDictionary rv = new System.Web.Routing.RouteValueDictionary(); if (Session["lastRouteValues"] != null) { rv = (System.Web.Routing.RouteValueDictionary)Session["lastRouteValues"]; } return RedirectToAction( rv["action"] == null ? "" : rv["action"].ToString() , rv); }else{ ViewBag.errors = rs; return View("index"); } }
// // GET: /Home/ public ActionResult Index() { System.Web.Routing.RouteValueDictionary rvd = new System.Web.Routing.RouteValueDictionary(); rvd.Add("controller", "Index"); rvd.Add("action", "Index"); return RedirectToRoute("Main_Default", rvd); }
public virtual ActionResult UpdateWizardStep(string key, string stepDirection) { if (string.IsNullOrEmpty(key)) { return(HttpNotFound()); } var state = GetWizard(key); RemoveValidationRulesFromOtherSteps(state); Validate(ModelState, state); ProcessToUpdate(state); UpdateWizard(state); TempData["WizardStep"] = state.CurrentStep; var routeData = new System.Web.Routing.RouteValueDictionary(state.CurrentStep); routeData.Add("Area", state.CurrentStep.GetActionUrl().Area); return(RedirectToAction( state.CurrentStep.GetActionUrl().Action, state.CurrentStep.GetActionUrl().Controller, new { Area = state.CurrentStep.GetActionUrl().Area })); }
public static MvcHtmlString PageLinks(this HtmlHelper html, UrlHelper url, PagingInfo inf) { StringBuilder ret = new StringBuilder(); ret.Append("<span class=\"button_link\">"); string action = html.ViewContext.RouteData.Values["action"].ToString(); System.Web.Routing.RouteValueDictionary routeVals = html.ViewContext.RouteData.Values; for (int i = 1; i <= inf.TotalPages; i++) { // RouteData.Values["controller"].ToString() routeVals["sort"] = inf.CurrentSortOption; routeVals["page"] = i; string urlRef = url.Action(action, routeVals); TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag tag.MergeAttribute("href", urlRef); tag.InnerHtml = i.ToString(); if (i == inf.CurrentPage) { tag.AddCssClass("selected"); } ret.AppendLine(tag.ToString()); } ret.Append("</span>"); return(MvcHtmlString.Create(ret.ToString())); }
public ActionResult Edit(FormCollection collection) { if (!AccessActions.IsAccess("Groups::Write")) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("err", "Нет доступа!"); return(RedirectToAction("Error", "User", route)); } try { GroupModel theGroup = new GroupModel(); theGroup.ID = Convert.ToInt32(collection["ID"]); theGroup.Name = collection["Name"]; theGroup.BranchID = Convert.ToInt32(collection["BranchID"]); if (theGroup.BranchID == 0) { UserModel theUser = new UserModel(); theGroup.BranchID = theUser.FindByID(UserModel.CurrentUserId).BrancheID; } theGroup.Update(collection["gr_abon_add"], collection["gr_abon_del"]); return(RedirectToAction("Index")); } catch (Exception ex) { ViewBag.Error = ex.Message; return(RedirectToAction("Index")); } }
public virtual System.Threading.Tasks.Task<CoreWebApiClient.TestControllers.AnotherTestDto> GetAsync(int id, string name, string value) { System.Web.Routing.RouteValueDictionary routeValues = new System.Web.Routing.RouteValueDictionary(); routeValues.Add("id", id); routeValues.Add("name", name); routeValues.Add("value", value); return this.HttpClientGetAsync<CoreWebApiClient.TestControllers.AnotherTestDto>("Get", routeValues); }
public ActionResult Devices(int id) { if (!Access.HasAccess(66)) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("err", "Нет доступа!"); return(RedirectToAction("Error", "Home", route)); } Device theModel = new Device(); ViewBag.Devices = (List <Device>)theModel.GetAll("REPOSITORY_ID=" + id.ToString()); Store theStore = new Store(); theStore = theStore.GetById(id); ViewBag.theStore = theStore; ViewBag.Stores = (new Store()).GetAll(); ViewBag.Devhistories = (List <Devhistory>)(new Devhistory()).GetAll("STORE_ID = " + id.ToString()); ViewBag.Devmodels = (List <Devmodel>)(new Devmodel()).GetAll(); Deviceadded theAdded = new Deviceadded(); return(View(theAdded)); }
public ActionResult ShowMaterials(int id, int MatmodelID) { if (!Access.HasAccess(66)) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("err", "Нет доступа!"); return(RedirectToAction("Error", "Home", route)); } ViewBag.StoreID = id; ViewBag.MatmodelID = MatmodelID; Matmodel theMatmodel = (new Matmodel()).GetById(MatmodelID); ViewBag.Matmodel = theMatmodel; ViewBag.Stores = (new Store()).GetAll(); ViewBag.Devices = (new Device()).GetAll(); ViewBag.Rooms = (new Room()).GetAll(); ViewBag.Materials = (new Material()).GetAll("MAT_MODEL_ID=" + ViewBag.MatmodelID); List <Material> theMaterials1 = (new Material()).GetAll("MAT_MODEL_ID=" + ViewBag.MatmodelID + " AND REPOSITORY_ID=" + ViewBag.StoreID + " AND STATUS_ID=1"); ViewBag.Materials1 = theMaterials1; ViewBag.Materials22 = ((List <Material>)ViewBag.Materials).Where(x => x.StatusID == 22).Where(x => x.Store.ID == ViewBag.StoreID); ViewBag.Materials3 = ((List <Material>)ViewBag.Materials).Where(x => x.StatusID == 3).Where(x => x.Store.ID == ViewBag.StoreID); ViewBag.Mathistory = (new Mathistory()).GetAll("STORE_ID=" + ViewBag.StoreID + " AND STATUS_ID=2"); return(View()); }
public ActionResult Create(FormCollection collection) { if (!Access.HasAccess(32)) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("err", "Нет доступа!"); return(RedirectToAction("Error", "Home", route)); } try { House model = new House(); model.Name = collection["Name"]; model.Street = (new Street()).GetById(Convert.ToInt32(collection["Street"])); int AreaID = 0; try { AreaID = Convert.ToInt32(collection["Area"]); model.Area = (new Area()).GetById(AreaID); } catch { } model.Save(model); return(RedirectToAction("Index")); } catch (Exception ex) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("err", ex.Message); return(RedirectToAction("Error", "Home", route)); } }
// // GET: /Store/Matmodels/5 public ActionResult Materials(int id) { if (!Access.HasAccess(66)) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("err", "Нет доступа!"); return(RedirectToAction("Error", "Home", route)); } Material theModel = new Material(); List <Material> theList = (List <Material>)theModel.GetAll("REPOSITORY_ID=" + id.ToString()); Store theStore = new Store(); theStore = theStore.GetById(id); ViewBag.theStore = theStore; ViewBag.Mathistory = ((List <Mathistory>)(new Mathistory()).GetAll()); ViewBag.Materials = (new Material()).GetAll(); ViewBag.Stores = (new Store()).GetAll(); ViewBag.Matmodels = (new Matmodel()).GetAll(); return(View(theList)); }
// // GET: /User/Edit/5 public ActionResult Edit(int id) { if (!AccessActions.IsAccess("User::Write")) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("err", "��� �������!"); return(RedirectToAction("Error", "User", route)); } UserModel user = new UserModel(); RoleModel role = new RoleModel(); BrancheModel branch = new BrancheModel(); ActionModel action = new ActionModel(); TypeModel type = new TypeModel(); //заполнение списка ролей ViewBag.Roles = role.FindAll(); //Заполнение списка филиалов ViewBag.AllBranches = branch.FindAll(); ViewBag.UserBranches = branch.UserBranches(id); ViewBag.UserActions = action.UserActions(id); ViewBag.AllActions = action.FindAll(); ViewBag.UserTypes = type.UserTypes(id); ViewBag.AllTypes = type.FindAll(); user.FindByID(id); ViewBag.UsName = user.Name; return(View(user)); }
public static MvcHtmlString SubPageMenuItem(this HtmlHelper helper, string linkText, string controller, string action, object routeValues, object htmlAttributes, object menuItemModel, string menuItemTemplateName) { string currentController = helper.ViewContext.RouteData.GetRequiredString("controller"); helper.ViewContext.RouteData.GetRequiredString("action"); var objTagBuilder = new TagBuilder("li"); IDictionary <string, object> htmlAttr = new System.Web.Routing.RouteValueDictionary(htmlAttributes); if (currentController.Equals(controller, StringComparison.InvariantCultureIgnoreCase)) { htmlAttr["class"] = htmlAttr["class"] + " active"; } objTagBuilder.MergeAttributes(htmlAttr); objTagBuilder.InnerHtml = helper.ActionLink(linkText, action, controller, routeValues, htmlAttributes).ToHtmlString(); //objTagBuilder.InnerHtml += "<i class=\"icon-nav-up-arrow\"></i>"; if (menuItemModel != null && !string.IsNullOrEmpty(menuItemTemplateName)) { objTagBuilder.InnerHtml += helper.Partial(menuItemTemplateName, menuItemModel).ToHtmlString(); } return(new MvcHtmlString(objTagBuilder.ToString())); }
public ActionResult Edit(int id, FormCollection collection) { if (!Access.HasAccess(8)) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("err", "Нет доступа!"); return(RedirectToAction("Error", "Home", route)); } try { // TODO: Add update logic here Branche theBranche = new Branche(); theBranche = theBranche.GetById(id); theBranche.FullName = collection["FullName"]; theBranche.ShortName = collection["ShortName"]; theBranche.Update(theBranche); return(RedirectToAction("Index")); } catch (Exception ex) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("err", ex.Message); return(RedirectToAction("Error", "Home", route)); } }
public ActionResult ShowDevices(int id, int DevmodelID) { if (!Access.HasAccess(66)) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("err", "Нет доступа!"); return(RedirectToAction("Error", "Home", route)); } ViewBag.StoreID = id; Store theStore = (new Store()).GetById(id); ViewBag.theStore = theStore; ViewBag.DevmodelID = DevmodelID; ViewBag.Stores = (new Store()).GetAll(); ViewBag.Rooms = (new Room()).GetAll(); ViewBag.Devices = (new Device()).GetAll("DEV_MODEL_ID=" + ViewBag.DevmodelID + " AND REPOSITORY_ID=" + id.ToString()); ViewBag.Devices1 = ((List <Device>)ViewBag.Devices).Where(x => x.StatusID == 1); ViewBag.Devices22 = ((List <Device>)ViewBag.Devices).Where(x => x.StatusID == 22); ViewBag.Devices2 = ((List <Device>)ViewBag.Devices).Where(x => x.StatusID == 2); ViewBag.Devices3 = ((List <Device>)ViewBag.Devices).Where(x => x.StatusID == 3); ViewBag.Devhistory = (new Devhistory()).GetAll("STORE_ID=" + ViewBag.StoreID + " AND STATUS_ID=2"); return(View()); }
private IEnumerable <RouteDataItemModel> ProcessRouteData(MvcRouteValueDictionary dataDefaults, RouteBase.GetRouteData.Message routeMessage) { if (dataDefaults == null || dataDefaults.Count == 0) { return(null); } var routeData = new List <RouteDataItemModel>(); foreach (var dataDefault in dataDefaults) { var routeDataItemModel = new RouteDataItemModel(); routeDataItemModel.PlaceHolder = dataDefault.Key; routeDataItemModel.DefaultValue = dataDefault.Value; if (routeMessage != null && routeMessage.Values != null) { routeDataItemModel.ActualValue = routeMessage.Values[dataDefault.Key]; } routeData.Add(routeDataItemModel); } return(routeData); }
public PageMenuItem(Page page) { base.Action = "Index"; base.Controller = "Page"; base.Area = "Sites"; base.Text = page.Name; if (page.Navigation != null && !string.IsNullOrEmpty(page.Navigation.DisplayText)) { base.Text = page.Navigation.DisplayText; } base.Tips = page.Name; base.Visible = true; RouteValues = new System.Web.Routing.RouteValueDictionary(); RouteValues.Add("parentPage", page.FullName); HtmlAttributes = new System.Web.Routing.RouteValueDictionary(); if (page.IsDefault) { HtmlAttributes.Add("class", "home"); } //this.Page = page; Initializer = new PageMenuItemInitializer(); }
public ActionResult Edit(int ID, FormCollection collection) { if (!Access.HasAccess(53)) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("err", "Нет доступа!"); return(RedirectToAction("Error", "Home", route)); } try { Devmodel model = new Devmodel(); model = model.GetById(ID); model.Name = collection["Name"]; model.Typedev = (new Typedev()).GetById(Convert.ToInt32(collection["Typedev.Id"])); model.Vendor = (new Vendor()).GetById(Convert.ToInt32(collection["Vendor.Id"])); model.Update(model); return(RedirectToAction("Index")); } catch (Exception ex) { ViewBag.Error = ex.Message; return(View()); } }
public ActionResult Compatibility(int ID, FormCollection collection) { if (!Access.HasAccess(51)) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("err", "Нет доступа!"); return(RedirectToAction("Error", "Home", route)); } Devmodel model = new Devmodel(); model = model.GetById(ID); string IDs = collection["MatmodelSelections"]; model.Matmodels.Clear(); model.Update(model); foreach (string item in IDs.Split(',')) { model.Matmodels.Add((new Matmodel()).GetById(Convert.ToInt32(item))); } model.Update(model); return(RedirectToAction("Index")); }
public ActionResult Edit(int id, FormCollection collection) { if (!AccessActions.IsAccess("Abonents::Write")) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("err", "Нет доступа!"); return(RedirectToAction("Error", "User", route)); } try { // TODO: Add update logic here AbonentModel theAbonent = new AbonentModel(); theAbonent.ID = id; theAbonent.Name = collection["Name"]; theAbonent.Phone = collection["Phone"]; theAbonent.Description = collection["Description"]; theAbonent.Email = collection["Email"]; theAbonent.BranchID = Convert.ToInt32(collection["BranchID"]); if (theAbonent.BranchID == 0) { UserModel theUser = new UserModel(); theAbonent.BranchID = theUser.FindByID(UserModel.CurrentUserId).BrancheID; } theAbonent.Update(); return(RedirectToAction("Index")); } catch (Exception ex) { ViewBag.Error = ex.Message; return(View()); } }
/// <summary> /// Converte o objeto para um Expando. /// </summary> /// <param name="obj"></param> /// <returns></returns> internal static ExpandoObject ToExpando(object obj) { IDictionary <string, object> expandoObject = new ExpandoObject(); var dic = new System.Web.Routing.RouteValueDictionary(obj); foreach (var o in dic) { expandoObject.Add(o.Key, o.Value == null || new[] { typeof(Enum), typeof(String), typeof(Char), typeof(Guid), typeof(Boolean), typeof(Byte), typeof(Int16), typeof(Int32), typeof(Int64), typeof(Single), typeof(Double), typeof(Decimal), typeof(SByte), typeof(UInt16), typeof(UInt32), typeof(UInt64), typeof(DateTime), typeof(DateTimeOffset), typeof(TimeSpan), }.Any(oo => oo.IsInstanceOfType(o.Value)) ? o.Value : ToExpando(o.Value)); } return((ExpandoObject)expandoObject); }
// // GET: /Home/ public ActionResult Index() { System.Web.Routing.RouteValueDictionary rvd = new System.Web.Routing.RouteValueDictionary(); rvd.Add("controller", "Index"); rvd.Add("action", "Index"); return(RedirectToRoute("Main_Default", rvd)); }
/// <summary> /// Transforms the outgoing route value using the inner projections in the reverse order. /// </summary> /// <param name="key">The route value key.</param> /// <param name="values">The route values.</param> public void Outgoing(string key, System.Web.Routing.RouteValueDictionary values) { foreach (var projection in projections.Reverse()) { projection.Outgoing(key, values); } }
public static MvcHtmlString SoftwareListSortOptions(this HtmlHelper html, UrlHelper url, WebUi.ViewModels.PagingInfo pagingData) { StringBuilder ret = new StringBuilder(); ret.AppendFormat("<div class=\"sort_options\"><span class=\"caption\">{0}</span>", UiResources.UiTexts.product_list_sort_order_caption); string action = html.ViewContext.RouteData.Values["action"].ToString(); System.Web.Routing.RouteValueDictionary routeVals = html.ViewContext.RouteData.Values; foreach (KeyValuePair <int, string> sortOption in DomainModel.Repository.Memory.ProductList.Instance.SortOptions) { routeVals["sort"] = sortOption.Key; routeVals["page"] = 1; string urlRef = url.Action(action, routeVals); TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag tag.MergeAttribute("href", urlRef); tag.InnerHtml = WebUi.Models.DynamicResources.GetText(sortOption.Value); if (sortOption.Key == pagingData.CurrentSortOption) { tag.AddCssClass("selected"); } ret.Append(tag.ToString()); ret.Append("<span class=\"pager_inf_separator\">.</span>"); } ret.Append("</div>"); return(MvcHtmlString.Create(ret.ToString())); }
public ActionResult Edit(int id, FormCollection collection) { if (!Access.HasAccess(38)) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("err", "Нет доступа!"); return(RedirectToAction("Error", "Home", route)); } try { Room model = new Room(); model = model.GetById(id); model.Name = collection["Name"]; model.House = (new House()).GetById(Convert.ToInt32(collection["House.Id"])); model.Update(model); return(RedirectToAction("Index")); } catch { return(View()); } }
/// <summary> /// Transforms the incoming route value using the inner projections in the direct order. /// </summary> /// <param name="key">The route value key.</param> /// <param name="values">The route values.</param> public void Incoming(string key, System.Web.Routing.RouteValueDictionary values) { foreach (var projection in projections) { projection.Incoming(key, values); } }
public ActionResult Create(FormCollection collection) { if (!AccessActions.IsAccess("Abonents::Write")) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("err", "Нет доступа!"); return(RedirectToAction("Error", "User", route)); } try { // TODO: Add insert logic here AbonentModel theAbonent = new AbonentModel(); //theAbonent.ID = Convert.ToInt32(collection["ID"]); theAbonent.Name = collection["Name"]; theAbonent.Phone = collection["Phone"]; theAbonent.Description = collection["Description"]; theAbonent.Email = collection["Email"]; theAbonent.Create(); return(RedirectToAction("Index")); } catch (Exception ex) { ViewBag.Error = ex.Message; return(View()); } }
public ActionResult ImageGallery(string id) { PlayerDashboardRepository modelRepo = new PlayerDashboardRepository(); var playerDashboard = modelRepo.ReadOne(id); string Reason = ""; if (modelRepo.ValidateLogin(playerDashboard, this, ref Reason)) { PlayerProgressGallery model = new PlayerProgressGallery(); model.PlayerID = playerDashboard.PlayerID; PlayerImagesRepository pImgRepo = new PlayerImagesRepository(); model.playerImages = pImgRepo.ReadAll(model.PlayerID.Value, false, false); ViewBag.PlayerProgressGallery = model; //Descrypt password return(View(playerDashboard)); } else { //Otherwise Redirect to Login Screen, if cookie didn't match then redirect to Login Page System.Web.Routing.RouteValueDictionary rt = new System.Web.Routing.RouteValueDictionary(); rt.Add("id", id); rt.Add("Reason", Reason); return(RedirectToAction("Login", rt)); } }
public void GetResult_LongExpression() { _controller.ModelState.AddModelError("LongExpr", "Выражение слишком длинное"); var jsonResult = _controller.GetResult(new CalculatorViewModel { Expression = new string('1', 201) }); var wrapper = new System.Web.Routing.RouteValueDictionary(jsonResult.Data); Assert.AreEqual(true, wrapper["HasError"]); }
public ActionResult Create(FormCollection collection) { if (!Access.HasAccess(52)) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("err", "Нет доступа!"); return(RedirectToAction("Error", "Home", route)); } try{ Devmodel model = new Devmodel(); model.Name = collection["Name"]; model.Printspeed = Convert.ToInt32(collection["Printspeed"]); model.Typedev = (new Typedev()).GetById(Convert.ToInt32(collection["TypedevID"])); model.Vendor = (new Vendor()).GetById(Convert.ToInt32(collection["VendorID"])); model.Capacity = Convert.ToInt32(collection["Capacity"]); model.Save(model); return(RedirectToAction("Index")); } catch (Exception ex) { ViewBag.Error = ex.Message; return(View()); } }
public ActionResult EditRole(string rl_act_add, string rl_act_del, FormCollection collection) { if (!AccessActions.IsAccess("RoleAction::Write")) { System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); route.Add("err", "Нет доступа!"); return(RedirectToAction("Error", "User", route)); } try { RoleModel theRole = new RoleModel(); theRole.ID = Convert.ToInt32(collection["ID"]); theRole.Name = collection["Name"]; theRole.Description = collection["Description"]; //theRole.UserId = UserModel.CurrentUserId; theRole.Update(collection["rl_act_add"], collection["rl_act_del"]); //theRole.Update(rl_act_add, rl_act_del); return(RedirectToAction("Index")); } catch (Exception ex) { ViewBag.Error = ex.Message; return(RedirectToAction("Index")); } }
public LanguageSpecificMenuItem(string language) { Action = "Index"; Language = language; RouteValues = new System.Web.Routing.RouteValueDictionary(); RouteValues.Add("culture", language); Initializer = new LanguageSpecificMenuItemInitializer(); }
void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) { if (AuthorizationCore.StaticCreate().IsGuest) { var url = filterContext.RequestContext.HttpContext.Request.RawUrl; var routeParams = new System.Web.Routing.RouteValueDictionary { { WebConstants.LoginRetUrlParameterName, url } }; filterContext.Result = new RedirectToRouteResult(WebConstants.LoginRouteName, routeParams); } }
public void GetResult_Correct() { var mock = new Mock<IExpressionEvaluator>(); mock.Setup(ld => ld.Evaluate("1+2")).Returns(new EvaluationResult(3)); _controller.ExpressionEvaluator = mock.Object; var jsonResult = _controller.GetResult(new CalculatorViewModel { Expression = "1+2" }); var wrapper = new System.Web.Routing.RouteValueDictionary(jsonResult.Data); Assert.AreEqual("3", wrapper["Result"]); }
public void GetResult_Error() { var mock = new Mock<IExpressionEvaluator>(); mock.Setup(ld => ld.Evaluate("1/0")).Returns(new EvaluationResult("ERR", 1)); _controller.ExpressionEvaluator = mock.Object; var jsonResult = _controller.GetResult(new CalculatorViewModel { Expression = "1/0" }); var wrapper = new System.Web.Routing.RouteValueDictionary(jsonResult.Data); Assert.AreEqual(true, wrapper["HasError"]); Assert.IsTrue(((string)wrapper["Result"]).StartsWith("ERR")); }
public static string SslRouteUrl(this UrlHelper urlHelper, string routeName, RouteValueDictionary routeValues, string hostName) { string protocol = null; bool foundProtocol = TryGetProtocol(routeName, out protocol) || TryGetProtocol(routeValues, out protocol) || TryGetProtocol(urlHelper.RequestContext.RouteData.Values, out protocol) || TryGetProtocolDefault(out protocol); return urlHelper.RouteUrl(routeName, routeValues, protocol, hostName); }
/// <summary> /// 网站语言设为美式英文 /// </summary> /// <returns>ActionResult.</returns> public ActionResult English(string returnUrl) { this.Session[SessionKey.Language] = LangEnum.EN_US; if (!String.IsNullOrEmpty(returnUrl)) { return Redirect(returnUrl); } System.Web.Routing.RouteValueDictionary rvd = new System.Web.Routing.RouteValueDictionary(); rvd.Add("controller", "Home"); rvd.Add("action", "Index"); return RedirectToRoute("Default", rvd); }
private static bool TryGetProtocol(RouteValueDictionary routeValues, out string protocol) { Ssl? ssl = null; if ((routeValues != null) && (routeValues.ContainsKey("controller"))) { ssl = RouteOptions.Current.GetOptionForValues(routeValues["controller"] as string); } protocol = ProtocolString(ssl); return ssl.HasValue; }
public LabelMenuItem(string name, string fullName, string culture) { base.Action = "index"; base.Controller = "label"; base.Area = "Sites"; base.Text = name; base.Visible = true; RouteValues = new System.Web.Routing.RouteValueDictionary(); RouteValues.Add("category", fullName); RouteValues.Add("culture", culture); this.Initializer = new LabelMenuItemInitializer(); }
public SiteMenuItem(Site site) { base.Action = "index"; base.Controller = "home"; base.Text = site.Name; if (!string.IsNullOrEmpty(site.DisplayName)) { base.Text = site.DisplayName; } base.Visible = true; RouteValues = new System.Web.Routing.RouteValueDictionary(); RouteValues["siteName"] = site.FullName; this.Initializer = new SiteMenuItemInitializer(); }
public RepositoryMenuItem(Repository repository) { base.Action = "index"; base.Controller = "Home"; base.Text = repository.Name; if (!string.IsNullOrEmpty(repository.DisplayName)) { base.Text = repository.DisplayName; } base.Visible = true; RouteValues = new System.Web.Routing.RouteValueDictionary(); RouteValues["repositoryName"] = repository.Name; this.Initializer = new RepositoryMenuItemInitializer(); }
public ViewNamespaceItem(Namespace<Kooboo.CMS.Sites.Models.View> ns) { base.Action = "index"; base.Controller = "view"; base.Area = "Sites"; base.Text = ns.Name; base.Visible = true; RouteValues = new System.Web.Routing.RouteValueDictionary(); RouteValues.Add("ns", ns.FullName); Initializer = new ViewNamespaceItemInitializer(); if (ns.ChildNamespaces != null) { this.Items = ns.ChildNamespaces.Select(it => new ViewNamespaceItem(it)).ToArray(); } }
/// <summary> /// Creates and Action link with a clickable image instead of text. /// </summary> /// <param name="helper"></param> /// <param name="controller">Controller</param> /// <param name="action">Action</param> /// <param name="parameters">Parameters</param> /// <param name="src">Image source</param> /// <param name="alt">Alternate text(Optional)</param> /// <returns>An HTML anchor tag with a nested image tag.</returns> /// public static MvcHtmlString OdrorirDelete(this HtmlHelper html, string linkText, string action, string controllerName, Guid id, object htmlAttributes) { var routeValues = new System.Web.Routing.RouteValueDictionary(); routeValues.Add("id", id); //build the tag linkText = string.Format("{0} <span class='glyphicon glyphicon-trash'></span>", linkText); TagBuilder tagBuilder = new TagBuilder("a"); tagBuilder.InnerHtml = linkText; //Add Url UrlHelper urlHelper = new UrlHelper(html.ViewContext.RequestContext); var url = urlHelper.Action(action, routeValues);//(action+"/"+id, controllerName); string modalVal = "deleteModal"; tagBuilder.MergeAttribute("href", url); tagBuilder.MergeAttribute("odrorir-dialogs", modalVal); //put it all together return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal)); }
public FolderMenuItem(Folder folder) { base.Visible = true; base.Text = folder.Name; RouteValues = new System.Web.Routing.RouteValueDictionary(); HtmlAttributes = new System.Web.Routing.RouteValueDictionary(); RouteValues["repositoryName"] = folder.Repository.Name; RouteValues["FolderName"] = folder.FullName; //compatible with the Folder parameter changed to FolderName. RouteValues["Folder"] = folder.FullName; this.Area = "Contents"; base.Text = folder.FriendlyText; var cssClass = ""; if (folder is TextFolder) { if (string.IsNullOrEmpty(((TextFolder)folder).SchemaName)) { base.Controller = "TextFolder"; base.Action = "Index"; } else { base.Controller = "TextContent"; base.Action = "index"; } cssClass = "TextFolder"; } else if (folder is MediaFolder) { base.Controller = "MediaContent"; base.Action = "index"; cssClass = "TextFolder"; } //Set folder class HtmlAttributes["Class"] = cssClass + " " + string.Join("-", folder.NamePaths.ToArray()); this.Initializer = new FolderMenuItemInitializer(); }
public ActionResult Handle(PolicyViolationException exception) { if (SecurityProvider.UserIsAuthenticated()) { return new ViewResult { ViewName = ViewName }; } else { var rvd = new System.Web.Routing.RouteValueDictionary(); if (System.Web.HttpContext.Current.Request.RawUrl != "/") rvd["ReturnUrl"] = System.Web.HttpContext.Current.Request.RawUrl; rvd["controller"] = "Account"; rvd["action"] = "LogOn"; rvd["area"] = ""; return new RedirectToRouteResult(rvd); } }
public override void OnActionExecuting(ActionExecutingContext filterContext) { var orderIdValue = filterContext.Controller.ValueProvider.GetValue("orderGuid"); if (orderIdValue != null) { Guid orderId = new Guid(orderIdValue.AttemptedValue); Order order = this.QueryDispatcher.Dispatch<Order, GetOrderQuery>(new GetOrderQuery(orderId)); if (order == null) { filterContext.Result = new RedirectToRouteResult(Routes.Checkout.Index, new System.Web.Routing.RouteValueDictionary()); } else { Guid? memberGuid = this.GetMemberGuid(filterContext.HttpContext); if (memberGuid.HasValue && memberGuid.Value == order.MemberGuid) { if (order.Status == Orders.Enums.OrderStatus.Complete || order.Status == Orders.Enums.OrderStatus.AwaitingShipment) { var routeData = new System.Web.Routing.RouteValueDictionary(); routeData.Add("orderGuid", orderId); filterContext.Result = new RedirectToRouteResult(Routes.Checkout.Complete, routeData); } } else { filterContext.Result = new RedirectToRouteResult(Routes.Checkout.Index, new System.Web.Routing.RouteValueDictionary()); } } } else { filterContext.Result = new RedirectToRouteResult(Routes.Checkout.Index, new System.Web.Routing.RouteValueDictionary()); } }
public ActionResult Index(string serviceOfferingIdName, string button) { ControllerUtilities.CheckFlags(this); System.Web.Routing.RouteValueDictionary route = new System.Web.Routing.RouteValueDictionary(); if (button == "Submit") { if (serviceOfferingIdName == null) { return this.Index(); } try { var newDesktop = mgr.CreateDesktop(serviceOfferingIdName); // For CPBM plugin return a simple view with VM Id visible if (ViewBag.NoLinks != null) { return View("CreateComplete", newDesktop); } route.Add("newId", newDesktop.Id); } catch (System.Exception ex) { CtxTrace.TraceError(ex); ViewBag.ErrorMessage = ex.Message; return View("Error"); } } return RedirectToAction("Index", "Manage", route); }
public ActionResult UploadPhoto([Bind(Include = "Name,Description")] PhotoFile file) { SaveObject obj; try { obj = PhotoHelper.SavePhoto(Request, Server, "Product", "FileUpload"); if (obj.isValid) { if (ModelState.IsValid) { file.FilePath = obj.FilePath; db.Photos.AddOrUpdate(file); db.SaveChanges(); Session.Add("FileID", file.PhotoId); } else { return View(file); } // ViewBag.ProdCategories = new SelectList(db.ProdCategories, "CategoryId", "Name"); string path = ""; PhotoEdit check = PhotoEdit.def; if (Session["EditUrl"] != null) { check = (PhotoEdit)Enum.Parse(typeof(PhotoEdit), Session["EditUrl"].ToString()); Session.Remove("EditUrl"); } int EditId = 0; if (Session["EditID"] != null) { EditId = Regex.IsMatch(Session["EditID"].ToString(), Variables.RegexForNumbers) ? Int32.Parse(Session["EditID"].ToString()) : -1; Session.Remove("EditID"); if (EditId == -1) { obj.Error.Add("Edit ID Problem or Something!"); ViewBag.Errors = obj; return View(); } } string prod = null; dynamic model = null; switch (check) { case PhotoEdit.Create: ViewBag.FileName = db.Photos.Find(file.PhotoId); ViewBag.ProdCategories = new SelectList(db.ProdCategories, "CategoryId", "Name"); path = "Create"; break; case PhotoEdit.EditProduct: TempData["FileName"] = db.Photos.Find(file.PhotoId); // model = db.Products.Find(); prod = "Products"; path = "Edit"; break; case PhotoEdit.Edit: model = db.Photos.Find(file.PhotoId); path = "EditPhoto"; break; default: return RedirectToAction("Index"); } System.Web.Routing.RouteValueDictionary routeValues = new System.Web.Routing.RouteValueDictionary(); routeValues.Add("id",EditId); return RedirectToAction(path,prod,routeValues); // return RedirectToAction("Create"); } else { ViewBag.Errors = obj.Error; return View(); } } catch (HttpException) { obj = new SaveObject(); obj.isValid = false; obj.Error.Add("The size of the file must be below 6mb"); return View(); } }
public ActionResult Create([Bind(Include = "Id,PostId,AuthorId,ParentCommentId,Level,Body,DisplayName,UpdateReason")] Comment comment, int? id, int? page, string anchor) { if (ModelState.IsValid) { comment.Created = DateTime.UtcNow; db.Comments.Add(comment); db.SaveChanges(); // @Html.ActionLink("Details", "Details", "Posts", null, null, //anchor, new { id = ViewBag.id, page = ViewBag.page }, null) var route = new System.Web.Routing.RouteValueDictionary(); route.Add("id", id); route.Add("page", page); route.Add("anchor", "#"+anchor); // The next line keeps failing, work on it later // var url = UrlHelper.GenerateUrl("", "Details", "Posts","http","",anchor, // route, null,Url.RequestContext, false); // return new RedirectResult(url); return RedirectToAction("Details", "Posts", route); } return View(comment); }
public ActionResult EditPhoto([Bind(Include = "Name,Description")] PhotoFile editfile, int? id) { string htmlattr = "FileUpload"; SaveObject Edit = new SaveObject(); if (!Regex.IsMatch(id.ToString(), Variables.RegexForNumbers)) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } if (Request.Files[htmlattr].ContentLength > 0) { Edit = PhotoHelper.EditPhoto((int)id, editfile, Request, Server, "Product", htmlattr); } else { PhotoFile file = db.Photos.Find(id); if (file == null) { return HttpNotFound(); } file.Description = editfile.Description; file.Name = editfile.Name; try { db.Photos.AddOrUpdate(file); db.SaveChanges(); Edit.isValid = true; } catch (Exception) { Edit.Error.Add("Something happened!"); Edit.isValid = false; } } if (Edit.isValid) { string path = ""; PhotoEdit check = PhotoEdit.def; if (Session["EditUrl"] != null) { check = (PhotoEdit)Enum.Parse(typeof(PhotoEdit), Session["EditUrl"].ToString()); Session.Remove("EditUrl"); } int EditId = 0; if(Session["EditID"] != null) { EditId = Regex.IsMatch(Session["EditID"].ToString(), Variables.RegexForNumbers) ? Int32.Parse(Session["EditID"].ToString()) : -1; Session.Remove("EditID"); if(EditId == -1) { Edit.Error.Add("Edit ID Problem or Something!"); ViewBag.Edit = Edit; return View(); } } string prod = null; dynamic model = null; switch (check) { case PhotoEdit.Create: ViewBag.FileName = db.Photos.Find(id); ViewBag.ProdCategories = new SelectList(db.ProdCategories, "CategoryId", "Name"); path = "Create"; break; case PhotoEdit.EditProduct: TempData["FileName"] = db.Photos.Find(id); // model = db.Products.Find(); prod = "Products"; path = "Edit"; break; case PhotoEdit.Edit: model = db.Photos.Find(id); path = "EditPhoto"; break; default: return RedirectToAction("Index"); } if(Session["FromEditProduct"] !=null) { bool ep = bool.Parse(Session["FromEditProduct"].ToString()); Session.Remove("FromEditProduct"); if(ep) { path = "Edit"; prod = "Products"; TempData["FileName"] = db.Photos.Find(id); } } System.Web.Routing.RouteValueDictionary routeValues = new System.Web.Routing.RouteValueDictionary(); routeValues.Add("id", EditId); return RedirectToAction(path, prod, routeValues); } ViewBag.Edit = Edit; return View(); }
public ActionResult Edit([Bind(Include = "Body,DisplayName,UpdateReason")] Comment comment, int? id, string anchor, int page, int? cid = null) { if (cid == null) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var route = new System.Web.Routing.RouteValueDictionary(); route.Add("id", id); route.Add("page", page); route.Add("anchor", "#" + anchor); if (ModelState.IsValid) { Comment orig = db.Comments.Find(cid); orig.Body = comment.Body; orig.DisplayName = comment.DisplayName; orig.UpdateReason = comment.UpdateReason; orig.Updated = DateTime.UtcNow; db.Entry(orig).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Details", "Posts", route); } return RedirectToAction("Details", "Posts", route); }
public ActionResult DeleteConfirmed(int? id, string anchor, int page, int? cid = null) { // Want to delete the comment (cid is its id, NOT id!) Comment comment = db.Comments.Find(cid); comment.Deleted = true; //db.Comments.Remove(comment); db.SaveChanges(); var route = new System.Web.Routing.RouteValueDictionary(); route.Add("id", id); route.Add("page", page); route.Add("anchor", "#" + anchor); // The next line keeps failing, work on it later // var url = UrlHelper.GenerateUrl("", "Details", "Posts","http","",anchor, // route, null,Url.RequestContext, false); // return new RedirectResult(url); return RedirectToAction("Details", "Posts", route); }
public virtual Eshop.Dtos.ProductDto GetProduct(int productId) { System.Web.Routing.RouteValueDictionary routeValues = new System.Web.Routing.RouteValueDictionary(); routeValues.Add("productId", productId); return this.HttpClientGet<Eshop.Dtos.ProductDto>("GetProduct", routeValues); }
public virtual System.Threading.Tasks.Task<Eshop.Dtos.ProductDto> GetProductAsync(int productId) { System.Web.Routing.RouteValueDictionary routeValues = new System.Web.Routing.RouteValueDictionary(); routeValues.Add("productId", productId); return this.HttpClientGetAsync<Eshop.Dtos.ProductDto>("GetProduct", routeValues); }
/**/ /// < summary> /// 分页Pager显示 /// < /summary> /// < param name="html">< /param> /// < param name="currentPageStr">标识当前页码的QueryStringKey< /param> /// < param name="pageSize">每页显示< /param> /// < param name="totalCount">总数据量< /param> /// < returns>< /returns> public static MvcHtmlString Pager(this HtmlHelper html, string currentPageStr, int pageSize, int totalCount) { var queryString = html.ViewContext.HttpContext.Request.QueryString; int currentPage = 1; //当前页 var totalPages = Math.Max((totalCount + pageSize - 1) / pageSize, 1); //总页数 html.ViewContext.RouteData.Values["action"] = html.ViewContext.RouteData.Values["action"].ToString().Replace("Part_", ""); var dict = new System.Web.Routing.RouteValueDictionary(html.ViewContext.RouteData.Values); var output = new System.Text.StringBuilder(); if (!string.IsNullOrEmpty(queryString[currentPageStr])) { //与相应的QueryString绑定 foreach (string key in queryString.Keys) if (queryString[key] != null && !string.IsNullOrEmpty(key)) dict[key] = queryString[key]; int.TryParse(queryString[currentPageStr], out currentPage); } else { //获取 ~/Page/{page number} 的页号参数 //int.TryParse(dict[currentPageStr].ToString(), out currentPage); int.TryParse(currentPageStr, out currentPage); } if (currentPage <= 0 || currentPage > totalPages) currentPage = 1; if (totalPages > 1) { if (currentPage != 1) { //处理首页连接 dict[currentPageStr] = 1; output.AppendFormat("{0} ", html.RouteLink("首页", dict)); } if (currentPage > 1) { //处理上一页的连接 dict[currentPageStr] = currentPage - 1; output.Append(html.RouteLink("上一页", dict)); } else { output.Append("<a>上一页</a>"); } output.Append(" "); int currint = 5; for (int i = 0; i <= 10; i++) { //一共最多显示10个页码,前面5个,后面5个 if ((currentPage + i - currint) >= 1 && (currentPage + i - currint) <= totalPages) if (currint == i) { //当前页处理 output.Append(string.Format("<a>{0}</a>", currentPage)); } else { //一般页处理 dict[currentPageStr] = currentPage + i - currint; output.Append(html.RouteLink((currentPage + i - currint).ToString(), dict)); } output.Append(" "); } if (currentPage < totalPages) { //处理下一页的链接 dict[currentPageStr] = currentPage + 1; output.Append(html.RouteLink("下一页", dict)); } else { output.Append("<a>下一页</a>"); } output.Append(" "); if (currentPage != totalPages) { dict[currentPageStr] = totalPages; output.Append(html.RouteLink("末页", dict)); } output.Append(" "); } if (totalPages != 1) { output.AppendFormat("{0} / {1}", currentPage, totalPages);//这个统计加不加都行 } return new MvcHtmlString(Uri.UnescapeDataString(output.ToString())); }