本文整理汇总了C#中System.Web.Mvc.ViewResult类的典型用法代码示例。如果您正苦于以下问题:C# ViewResult类的具体用法?C# ViewResult怎么用?C# ViewResult使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
ViewResult类属于System.Web.Mvc命名空间,在下文中一共展示了ViewResult类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C#代码示例。
示例1: HandleException
public static void HandleException(this ExceptionContext filterContext)
{
var ex = filterContext.Exception;
var contextResponse = filterContext.HttpContext.Response;
LogException(ex);
HttpException httpException = new HttpException(null, ex);
int httpExceptionCode = httpException.GetHttpCode();
string controllerName = (string)filterContext.RouteData.Values["controller"];
string actionName = (string)filterContext.RouteData.Values["action"];
HandleErrorInfo model = new HandleErrorInfo(ex, controllerName ?? "Unknown", actionName ?? "Unknown");
ViewResult result = new ViewResult
{
ViewName = "Error",
MasterName = "_Layout",
ViewData = new ViewDataDictionary<HandleErrorInfo>(model),
TempData = filterContext.Controller.TempData
};
filterContext.Result = result;
filterContext.ExceptionHandled = true;
contextResponse.Clear();
contextResponse.StatusCode = httpExceptionCode;
contextResponse.TrySkipIisCustomErrors = true;
}
开发者ID:garysharp,项目名称:Disco,代码行数:27,代码来源:HelperExtensions.cs
示例2: RequireHttpsAttributeRedirectsGetRequest
[InlineData(44300, "{0}:44300")] // Non-standard Port, Authenticated, always force SSL for this action
public void RequireHttpsAttributeRedirectsGetRequest(int port, string hostFormatter)
{
// Arrange
var mockAuthContext = new Mock<AuthorizationContext>(MockBehavior.Strict);
var mockConfig = new Mock<IAppConfiguration>();
var mockFormsAuth = new Mock<IFormsAuthenticationService>();
mockAuthContext.SetupGet(c => c.HttpContext.Request.HttpMethod).Returns("get");
mockAuthContext.SetupGet(c => c.HttpContext.Request.Url).Returns(new Uri("http://test.nuget.org/login"));
mockAuthContext.SetupGet(c => c.HttpContext.Request.RawUrl).Returns("/login");
mockAuthContext.SetupGet(c => c.HttpContext.Request.IsSecureConnection).Returns(false);
mockConfig.Setup(cfg => cfg.RequireSSL).Returns(true);
mockConfig.Setup(cfg => cfg.SSLPort).Returns(port);
var attribute = new RequireSslAttribute()
{
Configuration = mockConfig.Object
};
var result = new ViewResult();
var context = mockAuthContext.Object;
// Act
attribute.OnAuthorization(context);
// Assert
Assert.IsType<RedirectResult>(context.Result);
Assert.Equal("https://" + String.Format(hostFormatter, "test.nuget.org") + "/login", ((RedirectResult)context.Result).Url);
}
开发者ID:ashuthinks,项目名称:webnuget,代码行数:31,代码来源:RequireSslAttributeFacts.cs
示例3: Setup
public void Setup()
{
_viewResult = new ViewResult();
_model = new TestViewModel { Property1 = "test", Property2 = 3 };
_viewResult.ViewData.Model = _model;
_viewResultTest = new ViewResultTest(_viewResult, new ViewTestController());
}
开发者ID:robdmoore,项目名称:TestStack.FluentMVCTesting,代码行数:7,代码来源:ViewResultTestTests.cs
示例4: AssertGamingConsolesInViewBag
protected static void AssertGamingConsolesInViewBag(ViewResult viewResult)
{
var selectListItems = viewResult.ViewBag.GamingConsoles as IEnumerable<SelectListItem>;
selectListItems.Count().ShouldEqual(1);
selectListItems.First().Text.ShouldEqual("Console1");
selectListItems.First().Value.ShouldEqual("Console1");
}
开发者ID:tamizhvendan,项目名称:gameo,代码行数:7,代码来源:ControllerSpecBase.cs
示例5: OnException
public void OnException(ExceptionContext context)
{
if (HttpContext.Current != null)
HttpContext.Current.Items["CurrentlyProcessingException"] = true;
ErrorLog.GetDefault(HttpContext.Current).Log(new Error(context.Exception, HttpContext.Current));
BlogConfig blogConfig;
using(var session = DocumentStoreHolder.DocumentStore.OpenSession())
{
blogConfig = session.Load<BlogConfig>("Blog/Config") ?? BlogConfig.NewDummy();
}
var controllerName = (string) context.RouteData.Values["controller"];
var actionName = (string) context.RouteData.Values["action"];
var viewResult = new ViewResult
{
ViewName = "500",
ViewData = new ViewDataDictionary(new HandleErrorInfo(context.Exception, controllerName, actionName)),
ViewBag =
{
BlogConfig = blogConfig.MapTo<BlogConfigViewModel>()
}
};
context.ExceptionHandled = true;
context.HttpContext.Response.StatusCode = 500;
context.HttpContext.Response.TrySkipIisCustomErrors = true;
context.HttpContext.Response.Clear();
context.Result = viewResult;
}
开发者ID:TimmyBoy,项目名称:RaccoonBlog,代码行数:33,代码来源:ElmahHandleErrorAttribute.cs
示例6: GetPartialViewName
protected string GetPartialViewName(ViewResult viewResult, ControllerContext controllerContext)
{
var routeData = controllerContext.RequestContext.RouteData;
var viewName = viewResult.ViewName.NullIfEmpty() ?? routeData.GetRequiredString("action");
// Check for view name override (child actions only)
if (viewOverrideParameter.IsNotNullOrEmpty() && controllerContext.IsChildAction)
{
var overrideView = routeData.Values.GetOrDefault(viewOverrideParameter) as string;
if (overrideView.IsNotNullOrEmpty())
{
return overrideView;
}
}
// Otherwise use partial view prefix
if (viewName.IsNullOrEmpty())
{
throw new InvalidOperationException("View name cannot be null.");
}
var partialViewName = string.Concat(partialViewPrefix, viewName);
// check if partial exists, otherwise we'll use the same view but with no layout page
var partialExists = viewResult.ViewEngineCollection.FindPartialView(controllerContext, partialViewName).View != null;
return partialExists ? partialViewName : viewName;
}
开发者ID:jo3stevens,项目名称:Fabrik.Common,代码行数:28,代码来源:PartialViewResultFormatter.cs
示例7: BeEmpty_GivenNotEmpty_ShouldPass
public void BeEmpty_GivenNotEmpty_ShouldPass()
{
ActionResult result = new ViewResult();
Action a = () => result.Should().BeEmptyResult();
a.ShouldThrow<Exception>()
.WithMessage("Expected ActionResult to be \"EmptyResult\", but found \"ViewResult\"");
}
开发者ID:jrnail23,项目名称:FluentAssertions.MVC,代码行数:7,代码来源:ActionResultAssertions_Tests.cs
示例8: Login
public ViewResult Login(Usuario u)
{
rdnLogin rdn = new rdnLogin();
ViewResult vr = new ViewResult();
vr.ViewBag.Categorias = rdnCategoria.listarTodos();
vr.ViewBag.SubCategorias = rdnSubCategoria.listarTodos();
vr.ViewBag.Produtos = rdnProduto.listarTodos();
Usuario usuario = rdn.EftuaLogin(u);
if (usuario != null )
{
vr.ViewName = "sucesso";
Session["usuarioLogado"] = u;
}
else
{
vr.ViewName = ("index");
vr.ViewBag.Usuario = u;
vr.ViewBag.Mensagem = "Login ou senha inválidos.";
}
return vr;
}
开发者ID:webjefferson,项目名称:VendaMais,代码行数:26,代码来源:HomeController.cs
示例9: ProdutoListar
public ViewResult ProdutoListar(int cat = 0, int subcat = 0)
{
List<Produto> listaProduto = new List<Produto>();
ViewResult vr = new ViewResult();
if (cat != 0)
{
listaProduto = rdnProduto.listarTodos(cat);
vr.ViewBag.listaProduto = listaProduto;
}
if (subcat != 0)
{
listaProduto = rdnProduto.listarTodos(0, subcat);
vr.ViewBag.listaProduto = listaProduto;
}
if (subcat == 0 && cat == 0)
{
listaProduto = rdnProduto.listarTodos();
vr.ViewBag.listaProduto = listaProduto;
}
vr.ViewBag.Categorias = rdnCategoria.listarTodos();
vr.ViewBag.SubCategorias = rdnSubCategoria.listarTodos();
vr.ViewName = "ProdutoListar";
return vr;
}
开发者ID:webjefferson,项目名称:VendaMais,代码行数:30,代码来源:HomeController.cs
示例10: OnActionExecuting
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
string sign = filterContext.HttpContext.Request.Headers["x-svhoo-login"];
if (!string.IsNullOrEmpty(sign))
{
sign = Cryptography.Decrypt(sign, Cryptography.EncryptKey, Cryptography.EncryptIV, EncryptMode.DES);
string[] list = sign.Split('\n');
int sysNo = 0;
DateTime loginTime = DateTime.Now;
if (list.Length < 3
|| int.TryParse(list[1], out sysNo) == false
|| DateTime.TryParse(list[2], out loginTime) == false)
{
ViewResult view = new ViewResult();
view.ViewData = new ViewDataDictionary();
view.ViewData.Model = new Message() { Data = "Not Login", Type = MessageType.Error };
filterContext.Result = view;
return;
}
ServiceContext.CustomerID = sysNo;
ServiceContext.CustomerName = list[0];
ServiceContext.CustomerLoginTime = loginTime;
}
else
{
ViewResult view = new ViewResult();
view.ViewData = new ViewDataDictionary();
view.ViewData.Model = new Message() { Data = "Login Sign Error", Type = MessageType.Error };
filterContext.Result = view;
return;
}
base.OnActionExecuting(filterContext);
}
开发者ID:helong0911,项目名称:NCPro,代码行数:34,代码来源:LoginAuthenticationAttribute.cs
示例11: ExecuteResult
public override void ExecuteResult(ControllerContext context)
{
var response = context.HttpContext.Response;
var request = context.HttpContext.Request;
// TODO: Add logic for not authorized requests
string viewName = StatusCode == HttpStatusCode.NotFound ? NotFoundView : ErrorView;
// We need to clear both headers and content
// because Clear() doesn't clear the headers
// see: http://msdn.microsoft.com/en-us/library/system.web.httpresponse.clear.aspx
response.ClearHeaders();
response.ClearContent();
response.StatusCode = (int)StatusCode;
// Certain versions of IIS will sometimes use their own error page when
// they detect a server error. Setting this property indicates that we
// want it to try to render ASP.NET MVC's error page instead.
response.TrySkipIisCustomErrors = true;
if (request.IsAjaxRequest())
{
// TODO: Add logic for AJAX requests
}
var viewResult = new ViewResult
{
ViewName = viewName,
ViewData = ViewData ?? new ViewDataDictionary()
};
viewResult.ExecuteResult(context);
}
开发者ID:shizik,项目名称:ScaffR-Generated,代码行数:33,代码来源:ErrorResult.cs
示例12: OnException
public void OnException(ExceptionContext filterContext)
{
var loggerFactory = DependencyResolver.Current.GetService<ILoggerFactory>();
var logger = loggerFactory.GetLogger("MasterHandleError");
logger.LogException(filterContext.Exception);
var viewDataDictionary = new ViewDataDictionary();
viewDataDictionary[DataKeys.AllowRobots] = AllowRobots.None;
string errorMessage = null;
var portfotolioException = filterContext.Exception as PortfotolioException;
if (portfotolioException != null)
{
errorMessage = portfotolioException.Message;
}
viewDataDictionary.Model = new ModelError(errorMessage);
var viewResult = new ViewResult
{
ViewData = viewDataDictionary,
ViewName = "Error",
};
filterContext.Result = viewResult;
filterContext.HttpContext.Response.SetHttpHeader(filterContext.Exception);
filterContext.ExceptionHandled = true;
}
开发者ID:medvekoma,项目名称:portfotolio,代码行数:27,代码来源:MasterHandleErrorAttribute.cs
示例13: Application_Error
protected void Application_Error()
{
try
{
var logger = ObjectFactory.GetInstance<ILog>();
Exception exception = Server.GetLastError() ?? new Exception("Unable to get exception.");
logger.Fatal("An unhandled exception occurred.", exception);
}
catch
{ }
HttpContext ctx = HttpContext.Current;
ctx.Response.Clear();
RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
string controllerName = rc.RouteData.GetRequiredString("controller");
IControllerFactory factory = ControllerBuilder.Current.GetControllerFactory();
IController controller = factory.CreateController(rc, controllerName);
var cc = new ControllerContext(rc, (ControllerBase)controller);
var viewResult = new ViewResult { ViewName = "Error" };
viewResult.ExecuteResult(cc);
ctx.Server.ClearError();
}
开发者ID:escherrer,项目名称:EC2Utilities,代码行数:25,代码来源:Global.asax.cs
示例14: testing_that_AssertViewName_passing_the_correct_viewresult_viewname_should_pass
public void testing_that_AssertViewName_passing_the_correct_viewresult_viewname_should_pass()
{
ViewResult viewResult = new ViewResult();
viewResult.ViewName = "SomeName";
viewResult.AssertViewName("SomeName");
}
开发者ID:Trovarius,项目名称:MVCTestsEx,代码行数:7,代码来源:ViewResultExtesionsTests.cs
示例15: Application_Error
//Обработка ошибок для всего приложения
protected void Application_Error(object sender, EventArgs e)
{
string requestType=Request.RequestType;
if (requestType.Equals("GET"))
{
HttpContext ctx = HttpContext.Current;
Exception ex = ctx.Server.GetLastError();
var httpException = ex as HttpException;
if (httpException != null)
{
if (httpException.GetHttpCode() == 404)
{
ctx.Response.Clear();
RequestContext rc = ((MvcHandler)ctx.CurrentHandler).RequestContext;
IController controller = new HomeController(); // Здесь можно использовать любой контроллер
var context = new ControllerContext(rc, (ControllerBase)controller);
var viewResult = new ViewResult();
//страницы будут искаться в Views/Shared
viewResult.ViewName = "Error404";
viewResult.ViewData.Model = new HandleErrorInfo(ex, context.RouteData.GetRequiredString("controller"), context.RouteData.GetRequiredString("action"));
viewResult.ExecuteResult(context);
ctx.Server.ClearError();
}
}
}
}
开发者ID:sergei-startsev,项目名称:GZ-webApp,代码行数:32,代码来源:Global.asax.cs
示例16: HandleUnauthorizedRequest
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext, IFacebookApplication settings)
{
Contract.Requires(filterContext != null);
Contract.Requires(filterContext.HttpContext != null);
Contract.Requires(filterContext.HttpContext.Request != null);
Contract.Requires(filterContext.RouteData != null);
Contract.Requires(filterContext.Controller != null);
Contract.Requires(settings != null);
var model = new FacebookAuthorizeInfo(
GetLoginUrl(settings, filterContext.HttpContext, null),
Perms,
filterContext.HttpContext.Request.QueryString.AllKeys.Contains("error_reason"),
filterContext.RouteData.Values);
var viewResult = new ViewResult
{
MasterName = Master,
ViewName = View,
ViewData = new ViewDataDictionary<FacebookAuthorizeInfo>(model),
TempData = filterContext.Controller.TempData
};
filterContext.Result = viewResult;
}
开发者ID:nitzo,项目名称:MegaStarz,代码行数:25,代码来源:CanvasSoftAuthorizeAttribute.cs
示例17: OnAuthorization
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.Request.IsAuthenticated)
{
var User = (USER)filterContext.HttpContext.Session["USER"];
if (User != null)
{
if (!(User.ROLE.Name == "ADMINISTRATEUR" || User.ROLE.Name == "VENDEUR" ||
User.ROLE.Name == "CLIENT"))
{
ViewResult Result = new ViewResult();
Result.ViewName = "Error";
Result.ViewBag.ErrorMessage = "Accès réservé aux clients";
filterContext.Result = Result;
}
}
}else {
ViewResult Result = new ViewResult();
Result.ViewName = "Error";
Result.ViewBag.ErrorMessage = "Vous n'êtes pas authentifié";
filterContext.Result = Result;
}
}
开发者ID:ColinDuquesnoy,项目名称:ProjASPMVC,代码行数:25,代码来源:ClientAuthorize.cs
示例18: UnhandledError
public static void UnhandledError(ExceptionContext filterContext)
{
var exception = filterContext.Exception;
if (filterContext.HttpContext.Request.IsAjaxRequest())
{
var errorObject = new
{
ErrorMessage = exception.Message,
Stacktrace = exception.ToString()
};
filterContext.HttpContext.Response.StatusCode = 500;
filterContext.Result = new JsonResult()
{
JsonRequestBehavior = JsonRequestBehavior.AllowGet,
ContentType = "application/json",
Data = errorObject
};
return;
}
ErrorViewModel viewmodel = ErrorViewModel.CreateFromError(exception, "Unhandled Error Occured");
ViewDataDictionary viewData = new ViewDataDictionary
{
Model = viewmodel
};
ViewResult viewresult = new ViewResult();
viewresult.ViewName = "UnhandledError";
viewresult.ViewData = viewData;
filterContext.Result = viewresult;
}
开发者ID:gest01,项目名称:DomainArchitecture,代码行数:35,代码来源:ErrorViewBuilder.cs
示例19: ProdutoCadastrarSave
public ViewResult ProdutoCadastrarSave(Produto p)
{
ViewResult vr = new ViewResult();
rdnProduto rdn = new rdnProduto();
Mensagem msg = new Mensagem();
String resultado = rdnProduto.adicionar(p);
try
{
int id = Convert.ToInt32(resultado);
msg.Titulo = "Produto cadastrado com sucesso. Código: " + resultado;
msg.Conteudo = "Deseja cadastrar imagens para o produto cadasrtado?";
msg.botaoEsquerdoLink = "ProdutoCadastrarImagem";
msg.botaoEsquerdoTitulo = "Sim";
}
catch (Exception e)
{
msg.Titulo = "Erro ao inserir.";
msg.Conteudo = "Produto cadastrado com sucesso." + resultado + e;
}
vr.ViewBag.Categorias = rdnCategoria.listarTodos();
vr.ViewBag.SubCategorias = rdnSubCategoria.listarTodos();
vr.ViewBag.Resultado = resultado;
vr.ViewBag.Mensagem = msg;
vr.ViewName = "ProdutoLista";
return vr;
}
开发者ID:webjefferson,项目名称:VendaMais,代码行数:33,代码来源:ProdutoController.cs
示例20: AuthorizeValidationError
public static ActionResult AuthorizeValidationError(this Controller controller, AuthorizeRequestValidationException exception)
{
var roException = exception as AuthorizeRequestResourceOwnerException;
if (roException != null)
{
Tracing.Error(roException.Message);
var result = new ViewResult
{
ViewName = "ValidationError",
};
result.ViewBag.Message = roException.Message;
return result;
}
var clientException = exception as AuthorizeRequestClientException;
if (clientException != null)
{
Tracing.Error(clientException.Message);
return new ClientErrorResult(clientException.RedirectUri, clientException.Error, clientException.ResponseType, clientException.State);
}
throw new ArgumentException("Invalid exception type");
}
开发者ID:cotepatrice,项目名称:Thinktecture.IdentityServer.v2,代码行数:26,代码来源:Extensions.cs
注:本文中的System.Web.Mvc.ViewResult类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论