ActionResult IActionResultCreator.CreateResult(object data) { var result = new JsonResult(); result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; result.Data = data; return result; }
public JsonResult Current(UserModel user) { if (Session[CookieModel.UserName.ToString()] == null || string.IsNullOrEmpty(Session[CookieModel.UserName.ToString()].ToString())) { Redirect("Login/Index"); return null; } JsonResult json = new JsonResult() { ContentType = "text/html" }; if (Session[CookieModel.CurrentUser.ToString()]==null || Session[CookieModel.CurrentAdmin.ToString()] == null || string.IsNullOrEmpty(Session[CookieModel.CurrentUser.ToString()].ToString()) || string.IsNullOrEmpty(Session[CookieModel.CurrentAdmin.ToString()].ToString())) { try { DataSet dst = ServiceModel.CreateInstance().Client.GetCurrentUser(Session[CookieModel.UserName.ToString()].ToString()); if (dst == null) return null; if (dst.Tables.Count != 2) return null; StringBuilder sb = new StringBuilder(); foreach (DataRow drow in dst.Tables[1].Rows) { sb.Append(drow[0].ToString()); sb.Append(" "); } Session[CookieModel.CurrentUser.ToString()] = string.Format("登录用户:{0} ", dst.Tables[0].Rows[0][0].ToString()); Session[CookieModel.CurrentAdmin.ToString()] = string.Format("系统管理员:{0}", sb.ToString().Trim()); } catch { } } json.Data = new { current = Session[CookieModel.CurrentUser.ToString()].ToString(), admin = Session[CookieModel.CurrentAdmin.ToString()].ToString() }; return json; }
public JsonResult CategoryList(string e) { JsonResult rez = new JsonResult(); List<Category> cats = con.Categorys.OrderBy(c => c.Por).ToList(); rez.Data = RenderPartialViewToString("CategoryList", cats); return rez; }
//由未匹配科室表插入匹配科室 public JsonResult AddToCompDivision(string HospitalCode, string HZType, string HZCode, string Type, string Code) { var user = Session["CurrentUser"] as UserAndRole; var res = new JsonResult(); int TypeInt = Convert.ToInt32(Type); bool flag = _ServicesSoapClient.SetMpDivisionCmp(HospitalCode, TypeInt, Code, HZCode, "手动匹配", user.UserId, user.TerminalName, user.TerminalIP, user.DeviceType); if (flag) { flag = _ServicesSoapClient.ChangeStatusForTmpDivision(HospitalCode, HZType, HZCode, 2); if (flag) { res.Data = true; } else { res.Data = false; } } else { res.Data = false; } res.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return res; }
public JsonResult Get() { JsonResult result = new JsonResult(); //var t = bll.GetCompanyEventList(1, 500); // return Json(t, JsonRequestBehavior.AllowGet); return result; }
public JsonResult OAuthInit() { JsonResult jr = new JsonResult(); jr.ContentType = "text/json"; jr.JsonRequestBehavior = JsonRequestBehavior.AllowGet; try { Client Sina = null; OAuth oauth = new OAuth(CnfgConst.Sina_AppKey, CnfgConst.Sina_AppSecret, CnfgConst.Sina_CallbackUrl); Sina = new Client(oauth); //用cookie里的accesstoken来实例化OAuth,这样OAuth就有操作权限了 //if (!string.IsNullOrEmpty(code))//暂时无法获取到传回的URL //{ // var token = oauth.GetAccessTokenByAuthorizationCode(code); // string accessToken = token.Token; // Response.Cookies["AccessToken"].Value = accessToken; // jr.Data = new { isSuccess = true }; // //Response.Redirect("Default.aspx"); //} //else { string url = oauth.GetAuthorizeURL(); jr.Data = new { isSuccess = false, url = url }; } return jr; } catch (Exception) { throw; } }
public JsonResult DeleteRedirect(string id) { var result = new JsonResult(); try { if (String.IsNullOrEmpty(id)) { return result; } var redirectId = Int32.Parse(id); var redirect = Context.Redirects.FirstOrDefault(x => x.RedirectId == redirectId); Context.Redirects.Remove(redirect); Context.SaveChanges(); // recycle cache after save CachedObjects.GetRedirectsList(true); result.Data = new {success = true}; return result; } catch { result.Data = new { success = false }; return result; } }
/// <summary> /// Called by the ASP.NET MVC framework after the action method executes. /// </summary> /// <param name="filterContext">The filter context.</param> public override void OnActionExecuted(ActionExecutedContext filterContext) { if (filterContext == null || !filterContext.HttpContext.Request.IsAjaxRequest()) { return; } // Preparing Json object for AJAX.success processing in forms.js javascript string destinationUrl = string.Empty; if (filterContext.Result is RedirectResult) { var result = filterContext.Result as RedirectResult; destinationUrl = UrlHelper.GenerateContentUrl(result.Url, filterContext.HttpContext); } if (filterContext.Result is RedirectToRouteResult) { var result = filterContext.Result as RedirectToRouteResult; var helper = new UrlHelper(filterContext.RequestContext); destinationUrl = helper.RouteUrl(result.RouteValues); } // Rendered context is getting reloaded by AJAX.success in forms.js javascript if (filterContext.Result is ViewResult) { return; } var jsonResult = new JsonResult { Data = new { resultType = "Redirect", redirectUrl = destinationUrl } }; filterContext.Result = jsonResult; }
/// <param name="jsonResult">The <see cref="JsonResult" /> to convert to a <see cref="JsonpResult" />.</param> public JsonpResult(JsonResult jsonResult) { ContentEncoding = jsonResult.ContentEncoding; ContentType = jsonResult.ContentType; Data = jsonResult.Data; JsonRequestBehavior = jsonResult.JsonRequestBehavior; }
public ActionResult SearchKullaniciYetki(string searchAdi, string searchSoyadi, int? page) { var Jr = new JsonResult { JsonRequestBehavior = JsonRequestBehavior.AllowGet }; var KullaniciList = baglanti().Select<Kullanici>(); if (!string.IsNullOrEmpty(searchAdi)) { KullaniciList = KullaniciList.Where(p => p.adi.ToLower().Contains(searchAdi)).ToList(); } if (!string.IsNullOrEmpty(searchSoyadi)) { KullaniciList = KullaniciList.Where(p => p.soyadi.ToLower().Contains(searchSoyadi)).ToList(); } var Match = new YetkilendirmeViewModel() { }; Match.Kullanicilar = KullaniciList; if (KullaniciList != null) { var Result = RenderPartialViewToString("YetkilendirmeList", Match); Jr.Data = new[] { new { Status = "ok", results = Result, searchAdi = searchAdi } }; } return Jr; }
public JsonResult DeleteSchema(string id) { var result = new JsonResult() { Data = new { success = false, message = "There was an error processing your request." } }; if (String.IsNullOrEmpty(id)) { return result; } int moduleId = Int32.Parse(id); var module = Context.Schemas.FirstOrDefault(x => x.SchemaId == moduleId); Context.Schemas.Remove(module); var success = Context.SaveChanges(); if (success > 0) { BookmarkUtil.DeleteBookmarkForUrl("/admin/schemas/editschema/" + id + "/"); result.Data = new { success = true, message = "The schema has been successfully deleted." }; } return result; }
public ActionResult Delete(Guid id) { JsonResult jsresult = new JsonResult(); jsresult.ContentType = Consts.CONTENT_TYPE; jsresult.Data = new { result = bizSysMenu.DeleteSysMenuByID(id) }; return jsresult; }
protected override void OnException(ExceptionContext filterContext) { if (filterContext.HttpContext.IsCustomErrorEnabled || true) //IsCustomErrorEnabled always false if client is localhost or client and server IPs identical. True set to override. { filterContext.ExceptionHandled = true; // If this is an ajax request, return the exception in the response if (filterContext.HttpContext.Request.IsAjaxRequest()) { //if (HttpContext.Response.ContentType == "text/html") //{ // filterContext.HttpContext.Response.StatusCode = 500; // var json = new JsonResult(); // json.JsonRequestBehavior = JsonRequestBehavior.AllowGet; //SICHERHEITSPROBLEM: s. http://haacked.com/archive/2009/06/25/json-hijacking.aspx // json.Data = HttpUtility.UrlEncode(filterContext.Exception.Message); // +filterContext.Exception.StackTrace; // json.ExecuteResult(this.ControllerContext); //} //else //{ filterContext.HttpContext.Response.StatusCode = 500; var json = new JsonResult(); json.JsonRequestBehavior = JsonRequestBehavior.AllowGet; //SICHERHEITSPROBLEM: s. http://haacked.com/archive/2009/06/25/json-hijacking.aspx json.Data = HttpUtility.UrlEncode(filterContext.Exception.Message); // +filterContext.Exception.StackTrace; json.ExecuteResult(this.ControllerContext); //} } else { ViewData.Model = new System.Web.Mvc.HandleErrorInfo(filterContext.Exception, "ControllerName", "ActionName"); // Pass a flag to the view to tell it whether or not to show a the stack trace ViewBag.IsCustomErrorEnabled = true; //filterContext.HttpContext.IsCustomErrorEnabled; this.View("Error").ExecuteResult(this.ControllerContext); } } }
public JsonResult StartGame(PraetorianGameState playerSideChoosen) { var jResult = new JsonResult(); if(playerSideChoosen == PraetorianGameState.ASSASSINTURN) { //Human needs to make the first move, so set the game state and return out _Board.IsAssassinComputer = false; _Board.IsLegalMove = true; _Board.GameState = PraetorianGameState.ASSASSINTURN; PraetorianBoard.ComputerState = PraetorianGameState.PRAETORIANTURN; } else { _Board.IsAssassinComputer = true; PraetorianBoard.ComputerState = PraetorianGameState.ASSASSINTURN; PraetorianGameSetup pGame = new PraetorianGameSetup(_Board.Pieces.ToList(), new KeyValuePair<int, PraetorianPieceViewModel>(0, new PraetorianPieceViewModel() { })); var newBoard = pGame.ComputerMakeMove(GAMEDEPTH, true); _LastMove = new KeyValuePair<int, PraetorianPieceViewModel>(_iMoveNumber++, GetLastMovedPieceFromComputer(newBoard.BoardPieces, _Board.Pieces.ToList())); _MasterMoveList.Add(_LastMove); _Board.Pieces = newBoard.BoardPieces; _Board.GameState = PraetorianGameState.PRAETORIANTURN; _Board.IsLegalMove = true; } jResult = Json(_Board); return jResult; }
public JsonResult GatherNumbers(string runname) { var theColleciton = GetCollection(); var query = theColleciton.AsQueryable<ServerStat>() .Where(s => s.runName.ToLower() == runname.ToLower()) .ToList(); var someStats = query .GroupBy(stat => new { NodeName = stat.osHostName }) .Select(stat => new { NumberOfTransactions = stat.Count(), Node = stat.Key.NodeName }) .ToList(); var jsonObject = new JsonResult(); jsonObject.JsonRequestBehavior = JsonRequestBehavior.AllowGet; jsonObject.MaxJsonLength = int.MaxValue; jsonObject.Data = someStats; return jsonObject; }
public ActionResult GroceryInfo(string name) { ServiceHost.TraceLog.TraceDetail("GroceryInfo called with " + name); JsGroceryResults groceryResults = new JsGroceryResults(); var context = new GroceryContext(); List<GroceryReturnValue> grocery = new List<GroceryReturnValue>(); var groceryName = name.ToLower(); try { var groc = context.Groceries.Include("Category").OrderBy(g => g.Name).First(g => g.Name.StartsWith(groceryName)); grocery.Add(new GroceryReturnValue() { Name = groc.Name, Category = groc.Category.Name, ImageUrl = groc.ImageUrl }); ServiceHost.TraceLog.TraceDetail(String.Format("Found {0} category for {1}", groc.Category.Name, name)); } catch (Exception) { ServiceHost.TraceLog.TraceDetail("Could not find a category for " + name); } groceryResults.Count = grocery.Count; groceryResults.Groceries = grocery; JsonResult result = new JsonResult(); result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; result.Data = groceryResults; return result; }
public void SearchTest() { string q = "*"; string businessTitleFacet = ""; string postingTypeFacet = ""; string salaryRangeFacet = ""; string sortType = "featured"; double lat = 40.736224; double lon = -73.99251; int currentPage = 1; int maxDistance = 0; int zipCode = 10001; System.Web.Mvc.JsonResult result = (JsonResult)controller.Search( q, businessTitleFacet, postingTypeFacet, salaryRangeFacet, sortType, lat, lon, currentPage, zipCode, maxDistance); NYCJobsWeb.Models.NYCJob data = (NYCJobsWeb.Models.NYCJob)result.Data; Assert.IsTrue(data.Facets.Count > 0); Assert.IsTrue(data.Results.Count > 0); }
public ActionResult Login() { //Response.ContentType = "application/json"; //// Post方式下,取得client端传过来的数据 //if ("post".Equals(Request.HttpMethod.ToLower())) //{ // StreamReader reader = new StreamReader(Request.InputStream); // string json = HttpUtility.UrlDecode(reader.ReadToEnd()); // Response.Write(json); //} //// Get方式下,取得client端传过来的数据 //else //{ // Response.Write("[{\"title\":\"Java高级编程\"},{\"title\":\"C#高级编程\"},{\"title\":\"JavaScript高级编程\"}]"); //} //var d = Request.Params.GetValues("username"); string username = "******"+Request.Params["username"]; string age ="年龄:"+ Request.Params["age"]; var result = new JsonResult { Data = new { username, age }}; result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return result; }
public JsonResult GetMsg(int page, int pageSize) { JsonResult result = new JsonResult(); FeedBack bll = new FeedBack(); var t = bll.FindByPage(pageSize, page); return Json(t); }
protected void Application_Error() { var httpContext = HttpContext.Current; if (httpContext == null) return; var context = new HttpContextWrapper(System.Web.HttpContext.Current); var routeData = RouteTable.Routes.GetRouteData(context); var requestContext = new RequestContext(context, routeData); /* when the request is ajax the system can automatically handle a mistake with a JSON response. then overwrites the default response */ if (requestContext.HttpContext.Request.IsAjaxRequest()) { httpContext.Response.Clear(); var controllerName = requestContext.RouteData.GetRequiredString("controller"); var factory = ControllerBuilder.Current.GetControllerFactory(); var controller = factory.CreateController(requestContext, controllerName); var controllerContext = new ControllerContext(requestContext, (ControllerBase)controller); var jsonResult = new JsonResult { Data = new {success = false, serverError = "500"}, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; jsonResult.ExecuteResult(controllerContext); httpContext.Response.End(); } else { httpContext.Response.Redirect("~/Error"); } }
// GET api/Bill public object GetBillData(string url) { JsonResult jsonResult = new JsonResult(); try { using (var client = new WebClient()) { var jsonData = client.DownloadString(url); var jsonSerializerSettings = new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() }; object model; using (GlimpseTimeline.Capture("====> Get bills from Json URL AngularJS")) { model = CacheHandler.Get(homeAngularJSCacheKey, () => { return JsonConvert.DeserializeObject<BillModel>(jsonData, jsonSerializerSettings); }); } jsonResult = new JsonResult { Data = model, JsonRequestBehavior = JsonRequestBehavior.AllowGet }; } } catch (Exception ex) { Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception(ex.Message)); } return jsonResult.Data; }
/// <summary> /// 发送返回统一格式的JsonResult /// </summary> /// <param name="controller">控制器方法</param> /// <param name="message">消息</param> /// <param name="result">结果 ok error noLogin</param> /// <param name="data">数据</param> /// <param name="redirectURL">跳转URL</param> /// <returns></returns> public static JsonResult JsonResult(this Controller controller, E_JsonResult result, string message, object data, string redirectURL) { ResponseMsgInfo rpInfo; if (redirectURL != null && redirectURL != "") { rpInfo = new ResponseMsgInfo(); rpInfo.Result = result.ToString(); rpInfo.Message = message; rpInfo.Data = data; rpInfo.RedirectURL = controller.Url.Content(redirectURL); //注意转换成绝对路径 } else { rpInfo = new ResponseMsgInfo() { Result = result.ToString(), Message = message, Data = data }; } JsonResult jsr = new JsonResult(); jsr.Data = rpInfo; jsr.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return jsr; }
public JsonResult AddCategory(string name) { var result = new JsonResult(); if (!String.IsNullOrEmpty(name)) { using (var context = new DataContext()) { var newCategory = new BlogCategory { CategoryName = name, CreateDate = DateTime.Now, IsActive = true }; context.BlogCategories.Add(newCategory); context.SaveChanges(); result.Data = new {id = newCategory.CategoryId}; return result; } } return result; }
public JsonResult getLanguages(int page, int records, string orderBy, string orderDirection) { JsonResult result = null; var query = (from l in db.Language select new DTOLanguage { Id = l.Id, Name = l.Name, IsActive = l.IsActive, LngCdId = l.LanguageCode.Code }).OrderBy(string.Format("{0} {1}", orderBy, orderDirection)).Skip((records * page) - records).Take(records); result = new JsonResult() { Data = new { Languages = query.ToList(), Count = (from l in db.Language select l).Count() } }; return result; }
public JsonResult AddRedirect(String source, String destination, Boolean isPermanent, Boolean rootMatching) { var result = new JsonResult(); try { var redirect = new Redirect { Source = source, Destination = destination, IsPermanent = isPermanent, RootMatching = rootMatching, DateModified = DateTime.UtcNow, IsActive = true }; Context.Redirects.Add(redirect); Context.SaveChanges(); result.Data = new { id = redirect.RedirectId, success = true }; CachedObjects.GetRedirectsList(true); return result; } catch { result.Data = new { success = false }; return result; } }
public override void OnAuthorization(AuthorizationContext filterContext) { var userSession = filterContext.HttpContext.Session[Constants.CurrentUserKey]; if (userSession != null) { var loginUser = (LoginUser)userSession; var verifyPass = false; foreach (var role in roles) { var roleCode = (int)role; if ((loginUser.Role & roleCode) == roleCode) { verifyPass = true; break; } } if (!verifyPass) { var result = new System.Web.Mvc.JsonResult(); result.Data = IoC.Resolve<IJsonSerializer>().Serialize(new DotPay.Web.Admin.JsonResult(-44)); filterContext.Result = result; base.OnAuthorization(filterContext); } } }
public ActionResult ChangePwd() { // AppointInfo model = new AppointInfo(); JsonResult result = new JsonResult(); var username = Request["username"].ToString(); var newpwd = Request["newpwd"].ToString(); var oldpwd = Request["oldpwd"].ToString(); try { AuthenticationBLL bll = new AuthenticationBLL(); var t = bll.ChangePwd(username, oldpwd, newpwd); if (t == true) { result.Data = true; } else { result.Data = false; } HttpCookie cookie = Cookie.Get("jlgl_user"); if (cookie != null) { Cookie.Remove("jlgl_user"); } } catch (Exception ex) { result.Data = false; } return result; }
public JsonResult AddRolesToGroups(FormCollection form) { JsonResult jr = new JsonResult(); MxUser mxUser = GetMxUser(); try { if (mxUser.IsInRole("GROUP_Edit")) { BLL.Groups.UpdateRoleInGroups(form["groups"].Replace("addRole_", ""), form["role"]); jr = Json(new { success = "true" }); } else { jr = Json(new { success = "false", error = "User does not have Group Edit rights" }); } } catch (Exception ex) { jr = Json(new { success = "false", error = ex.Message }); } return jr; }
public NewtonJsonResult(JsonResult result) { this.ContentEncoding = result.ContentEncoding; this.Data = result.Data; this.ContentType = result.ContentType; this.JsonRequestBehavior = result.JsonRequestBehavior; }
public async Task <ActionResult> Index1() { List <CanvasCourseModel> viewModel = new List <CanvasCourseModel>(); ActionResult courses = await GetAllCourses(); if (courses != null) { System.Web.Mvc.JsonResult result = courses as JsonResult; if (result != null) { string json = base.serializer.Serialize(result.Data); if (!string.IsNullOrEmpty(json)) { var allCourses = result.Data.FromJson <List <CanvasCourseModel> >(); if (allCourses != null) { allCourses = (from c in allCourses orderby c.name select c) .ToList(); viewModel = allCourses; } } } } return(View(viewModel)); }
public JsonResult Get(int typeid, int page, int pageSize) { JsonResult result = new JsonResult(); StaffStarBLL bll = new StaffStarBLL(); var t = bll.GetStaffStarList(typeid, page, pageSize); return Json(t, JsonRequestBehavior.AllowGet); }
public JsonResult Get(int page, int pageSize) { JsonResult result = new JsonResult(); FeedBack bll = new FeedBack(); var t = bll.FindByPage(pageSize, page); return Json(t, JsonRequestBehavior.AllowGet); }
// GET: Canvas public async Task <ActionResult> Index1() { CanvasManager cm = new CanvasManager(); await cm.GetCourseDetail(100); await cm.Execute(CanvasCommand.GET_COURSE_LIST); CanvasDashboardModel viewModel = new CanvasDashboardModel(); ActionResult courses = await GetAllCourses(); if (courses != null) { System.Web.Mvc.JsonResult result = courses as JsonResult; if (result != null) { string json = base.serializer.Serialize(result.Data); if (!string.IsNullOrEmpty(json)) { var allCourses = result.Data.FromJson <List <CanvasCourseModel> >(); if (allCourses != null) { allCourses = (from c in allCourses orderby c.name select c) .ToList(); viewModel.Courses = allCourses; } } } } return(View("~/Areas/Canvas/Views/Canvas/CanvasDashBoard.cshtml", viewModel)); }
/// <summary> /// 根据数据层的操作 来返回不同的json数据 /// </summary> /// <param name="result">数据库返回的数据 受影响行数或者被插入数据的id</param> /// <param name="modelCount">待处理的数据条数</param> /// <param name="msg">弹框显示信息</param> /// <param name="opraterType">0 insert 1 update 2 delete 3 后台模型校验不通过 ,4 登录超时</param> /// <param name="data">后台josn 数据返回</param> /// <param name="backUrl">前台处理完成后跳转页面</param> /// <returns></returns> public static JsonResult CreatJavaScriptResult(int result, int modelCount, string msg, int opraterType, string data, string backUrl) { AjaxMsgModel ajax = new AjaxMsgModel() { Statu = CommonHelp.EnumHelper.Results.失败.ToString(), Msg = "系统错误", Data = data, BackUrl = backUrl }; if (opraterType == 0) { if (result > modelCount) { ajax = new AjaxMsgModel() { Statu = CommonHelp.EnumHelper.Results.成功.ToString(), Msg = msg, Data = data, BackUrl = backUrl }; } } else if (opraterType == 3) { ajax = new AjaxMsgModel() { Statu = "noValid", Msg = msg, Data = data, BackUrl = backUrl }; } else if (opraterType == 4) { ajax = new AjaxMsgModel() { Statu = "nologin", Msg = msg, Data = data, BackUrl = backUrl }; } else { if (result == modelCount) { ajax = new AjaxMsgModel() { Statu = CommonHelp.EnumHelper.Results.成功.ToString(), Msg = msg, Data = data, BackUrl = backUrl }; } } JsonResult res = new JsonResult(); res.Data = ajax; // res.JsonRequestBehavior = JsonRequestBehavior.AllowGet; return(res); }