I am trying a login example. In the controller class i am using addError method to display error. When i enter invalid entries it goes to the error page, but doesn't display the message.Success page works fine.
LoginController.java
#Controller
public class LoginController {
#Autowired
private LoginService loginService;
#RequestMapping("login.html")
public String toLogin(Model model) {
Login login = new Login();
model.addAttribute("login",login);
return "login";
}
#RequestMapping(value ="login.html", method = RequestMethod.POST)
public ModelAndView doLogin(#Valid #ModelAttribute ("login") Login login,
BindingResult bindingresult ) {
ModelAndView view = new ModelAndView("login");
if(!bindingresult.hasErrors()){
if(!loginService.authenticateUser(login)){
bindingresult.addError(new ObjectError("invalid", "Invalid Credentials"));
return new ModelAndView("error");
}
else{
view.setViewName("success");
}
}
return view;
}
}
error.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>LoginExample2-Error</title>
</head>
<body>
<table>
<tr>
<td>Retry</td>
</tr>
</table>
</body>
</html>
Related
I have implemented an action filter attribute for token verification and if token is invalid then api response should return from this action filter.
public class TokenValidationAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
bool isValidToken = FunctionToVerifyToken();
if (!isValidToken ))
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
{
Content = new StringContent("Unauthorized user")
};
return;
}
}
}
Response:
It goes to _layout.cshtml and returns whole html page instead of just returning "Unauthorized user"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Sign in</title>
<link href="/favicon.ico" rel="shortcut icon" type="image/x-icon" />
<meta name="viewport" content="width=device-width" />
<link href="/Content/styles.css" rel="stylesheet"/>
<script src="/Scripts/modernizr-2.8.3.js"></script>
...
Update:
controller where I'm using this token:
public class ServiceController : ApiController
{
[AcceptVerbs("GET", "POST")]
[HttpGet]
[HttpPost]
[TokenValidation]
public object ChangePassword()
{
//my logic is token is valid. It returns json data and works fine.
}
}
The view returned is login page.
My WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{action}/{id}",
defaults: new { controller = "Service", id = RouteParameter.Optional },
constraints: null
);
}
}
In Global.ascx.cs add following line
GlobalConfiguration.Configure(FilterConfig.Register);
In FilterConfig.cs register method
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new TokenValidationAttribute());
}
I think your code are missing this below lines in your TokenValidationAttribute.cs action filter.
base.OnActionExecuting(actionContext); return; What this will do is it would get your formated result and display your result rather than displaying the view.
I returned response as:
actionContext.Response = actionContext.Request.CreateResponse<string>(HttpStatusCode.BadRequest, "Unauthorized user");
and it returned "Unauthorized user" instead of whole html page.
I would like to use ViewBag values in the shared view of layout but provided from another controller. In particular, I would like to render the principal action and then add few variables, coming from another controller, that are used in a lot of pages (but not in all pages to justify the use of global variables).
Views/Shared/_Layout.cshtml
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
#Styles.Render("~/Content/css_custom")
#Scripts.Render("~/bundles/modernizr")
</head>
<body>
#Html.Action("myAction", "myController")
<p>Value: #ViewBag.testval </p>
#RenderBody()
</body>
</html>
Controllers/myController.cs
namespace myProject.Controllers
{
public class myController : Controller
{
public void myAction() {
string test_value = "Hey!";
ViewBag.testval = test_value;
}
}
}
In the layout the only Viewbag variables that I can access are the ones of the action target of RenderBody.
You should return that view.
public ActionResult Index()
{
ViewBag.testval = "Test value";
return View();
}
im just start learning asp.net and encounter this error
i've tried many solution from google but still get this error (errr...)
Compiler Error Message: CS1061: 'Exercise1.Visitor' does not contain a definition for 'Name' and no extension method 'Name' accepting a first argument of type 'Exercise1.Visitor' could be found (are you missing a using directive or an assembly reference?)
im using VS2012 with 4.5 Net
this is my code
Model
namespace Exercise1.Models
{
public class Visitor
{
public String Name
{
set;
get;
}
}
}
Controller
namespace Exercise1.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Visitor data)
{
ViewBag.Message= "Hi my name is" + data.Name;
return View();
}
}
}
View
#{
Layout = null;
}
#model Exercise1.Visitor
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title></title>
</head>
<body>
<div>
#using(Html.BeginForm())
{
<p>
#Html.LabelFor(m=>m.Name);
</p>
}
</div>
</body>
</html>
btw, this is my first question hehe
Change model to:
#using Exercise1.Models
#model Exercise1.Models.Visitor
Do you have another Vistor class in your project? it's saying Exercise1.Visitor when it should be complaining about Exercise1.Models.Visitor
make sure you're referencing Exercise1.Models.Visitor
I create Spring MVC project like this.
This is Controller:
#Controller
public class HelloWorldController {
#RequestMapping("/hello")
public String doHello(Model model) {
model.addAttribute("message", "Hello Spring MVC");
return "helloworld";
}
}
And this is content of file "helloworld.jsp".
<body> <h1>${message }</h1> </body> // I don't know why I can't post full code
When i run URL "http://localhost:8080/HelloSpringMVC/hello", the result should be Hello Spring MVC but I got ${message }, what's going on?
Make sure you have javax expression language dependency in your project.
add <%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> to jsp file.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello ${message }
</h1>
</body>
</html>
try this:
#Controller
public class HelloWorldController {
#RequestMapping("/hello")
public ModelAndView doHello() {
ModelAndView model = new ModelAndView("helloworld");
model.addObject("message", "Hello Spring MVC");
return model;
}
}
Using ASP.NET MVC4 (.NET 4, C#) on MSVC 2010 SP1, I've noticed that I can pass a class model to a view using Razor and display the model using DisplayModelFor & EditorForModel but when I try to do the same using the ASPX view engine it doesn't work. Why is that? Code snippets from my test project below. Thanks.
My Controller:
namespace MvcApplication1.Controllers
{
public class TestController : Controller
{
public ActionResult Index()
{
TestModelClass c = new TestModelClass();
c.MyInt = 999;
return View(c);
}
}
My Model:
namespace MvcApplication1.Models
{
public class TestModelClass
{
public int MyInt { get; set; }
}
}
My View:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<MvcApplication1.Models.TestModelClass>" %>
<!DOCTYPE html>
<html>
<head runat="server">
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<%Html.DisplayForModel(); %>
</div>
</body>
</html>
Alternate Razor (Works):
#model MvcApplication1.Models.TestModelClass
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#Html.DisplayForModel()
Successful output from Razor version:
Index
MyInt
999
You are missing a :.
The correct syntax should be
<%: Html.DisplayForModel() %>