本文整理匯總了C#中System.Web.Mvc.ViewResult類的典型用法代碼示例。如果您正苦於以下問題:C# ViewResult類的具體用法?C# ViewResult怎麽用?C# ViewResult使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。
ViewResult類屬於System.Web.Mvc命名空間,在下文中一共展示了ViewResult類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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;
}
示例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);
}
示例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());
}
示例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");
}
示例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;
}
示例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;
}
示例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\"");
}
示例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;
}
示例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;
}
示例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);
}
示例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);
}
示例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;
}
示例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();
}
示例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");
}
示例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();
}
}
}
}