I have a redirection problem in ASP.NET, I have in the folder view the _Layout.cshtml or there is the home page and I created a second page BookingChamb.cshtml in the same folder. I have created a link in the submit button on the home page (<a href="">) to page BookingChamb.cshtml, but the page is not showing and I received this message :
"Server Error in '/' Application. The resource can not be found.
Description: HTTP 404. The resource you are looking for (or one of its
dependencies) could have been removed, had its name changed, or is
temporarily unavailable. Please review the following URL and make sure
that it is spelled correctly.
Requested URL: /BookingChamb.cshtml "
Thank you in advance
In asp.net-mvc you cannot link directly to a view, you need a backing controller action:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page";
return View();
}
public ActionResult BookingChamb()
{
return View();
}
}
And then generate your link with:
#Html.ActionLink("Booking","Home","BookingChamb")
here is the link code in the _Layout.cshtml page :
<button class="btn-submit" type="submit"> chercher</button>
here is the link code in the HomeController page :
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Title = "Home Page";
return View();
}
}
here is the folder structure
enter image description here
Related
I want to display a hyperlink in browser and when I click on the hyperlink the request goes to my controller and open the URL in new tab of the browser.
Any idea how can I achieve this?
#*This is index.cshtml*#
#{
ViewBag.Title = "Index";
}
<h2>Click on the link below</h2>
#Html.ActionLink("GOOGLE", "NewWindow", "Home")
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
public ActionResult NewWindow()
{
return Content("<script>window.open('https://www.google.com/','_blank')</script>");
}
}
}
This code is showing error. Please help
Use target="_blank" to open a link in a new window.
#Html.ActionLink("GOOGLE", "RedirectToGoogle", "Home", null, new { target = "_blank" })
In the controller, return a redirection to the required URL:
public ActionResult RedirectToGoogle()
{
return Redirect("https://www.google.com/");
}
Overview: I am currently attempting to build a create account form. The form is rendered on another razor page. All works correctly, the form displays, sends the form data to a controller, sends data to a class, performs all DB actions, but then upon the completion of the previous items , the program attempts to find a page "CreateAccount.something" when all I want it to do for the time being is to return the initial view upon the return call.
Within said project, a form is displayed via: #RenderPage("~/Views/Home/AccountCreationForm.cshtml")
The form:
#model SuperDuperProject.Models.AccountCreationModel // AccountCreationModel is only a class file containing the necessary variables
...
#using (Html.BeginForm("CreateAccount", "Home", FormMethod.Post))
{
<table cellpadding="0" cellspacing="0">
...
#Html.TextBoxFor(m => m.name)
...
<input type="submit" value="Submit"/>
</table>
}
The Controller file (HomeController.cs):
...
public ActionResult UserLogin() // the page containing the form
{
return View();
}
[HttpPost]
public ActionResult CreateAccount(AccountCreationModel ACM)
{
Console.WriteLine("CreateAccount within HomeController");
Helpers.CreateAccount a = new Helpers.CreateAccount(...);
a.AccountCreationQuery();
return Index(); // ********** Doesn't seem to operate correctly **********
}
Instead of returning Index() or anything placed there, the program attempts to find a CreateAccount view that does not exist.
What am I missing so I can simply return to a desired page, such as Index?
Any assistance would be greatly appreciated.
[HttpPost]
public ActionResult CreateAccount(AccountCreationModel ACM)
{
Console.WriteLine("CreateAccount within HomeController");
Helpers.CreateAccount a = new Helpers.CreateAccount(...);
a.AccountCreationQuery();
return RedirectToAction("Index");
// return Redirect("Home/Index"); alternatively can use Redirect
}
You could consider using RedirectToAction or Redirect.
RedirectToAction returns an HTTP 302 response to the browser, which causes the browser to make a GET request to the specified action. Redirect takes a string type URL parameter and redirects to that specified the URL.
Check out this post for more info:
https://www.codeproject.com/Articles/595024/Controllers-and-Actions-in-ASP-NET-MVC
Try this code
public ActionResult UserLogin() // the page containing the form
{
return View();
}
[HttpPost]
public ActionResult CreateAccount(AccountCreationModel ACM)
{
Console.WriteLine("CreateAccount within HomeController");
Helpers.CreateAccount a = new Helpers.CreateAccount(...);
a.AccountCreationQuery();
return View("Index"); //index is the view here. You can define the view //name which you want to return from this controller action
}
By default controller searches for the view name as the name of the controller action that's why it is attempting to locate the view CreateAccount because controller action name is CreateAccount.
I am trying to create an MVC 4 ASP.net site. As I am new to programming I would like to know what is the correct way of rendering a view based on if a user is logged in or not.
My Code: I am trying to restrict a user from going to the Index, About and Contact pages. It will only go to those pages(views) if the user is Logged In. My question is, "Is this the right way of doing it or is this wrong? Is there a more secure, effective, and acceptable way of doing this?"
Please let me know if there is. Thank You
public class HomeController : Controller
{
public ActionResult Index()
{
if (User.Identity.IsAuthenticated)
{
return View();
}
return RedirectToRoute(new { controller = "Account", action = "Login" });
}
public ActionResult About()
{
if (User.Identity.IsAuthenticated)
{
ViewBag.Message = "Your app description page.";
return View();
}
return RedirectToRoute(new { controller = "Account", action = "Login" });
}
public ActionResult Contact()
{
if (User.Identity.IsAuthenticated)
{
ViewBag.Message = "Your contact page.";
return View();
}
return RedirectToRoute(new { controller = "Account", action = "Login" });
}
The Authorize attribute lets you indicate that authorization is restricted to predefined roles or to individual users.
This gives you a high degree of control over who is authorized to view any page on the site.
If an unauthorized user tries to access a method that is marked with the Authorize attribute, the MVC framework returns a 401 HTTP status code.
If the site is configured to use ASP.NET forms authentication, the 401 status code causes the browser to redirect the user to the login page.
You can use [Authorize] on your controller if all the methods require login as below:
[Authorize]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
You can also put the attribute on certain methods if required instead of putting on the controller itself. For example, if you want the user to login for Index() method only then you could do it as below:
public class HomeController : Controller
{
[Authorize]
public ActionResult Index()
{
return View();
}
}
The common way for this case is usage of [Authorize] (AuthorizeAttribute)
You may add it to specific Actions or whole Controller. It either supports specific users restrictions and Roles as well.
You may start with default MVC solution from Visual Studio, which will create all basic functionality based on SimpleMembership provider.
You may refer to NerdDinner project for full explanation: http://nerddinnerbook.s3.amazonaws.com/Part9.htm.
I am trying to redirect to action and get a new view (a new page) with no success. While debugging, I'm reaching the controller but not getting the view (the page URL is not changed).
With Fiddler I see that the page returns the right view result but in the browser the URL is not changed!
When shopping cart is empty, I would like to redirect to a new page a display the error message.
[HttpPost]
public ActionResult PlaceOrder(DeliveryDetails deliveryDetails)
{
if (UserCart.IsEmpty)
{
TempData["errorMsg"] = "Error: Cart is empty";
return RedirectToAction("Index", "Error");
}
else
{
// do something..
}
}
ErrorController:
public ActionResult Index()
{
return View();
}
ErrorController View:
#TempData["errorMsg"]
Any suggestions on what is going on ?
It was a js problem:
event.isDefaultPrevented()
Is your 'ErrorController View:' should be named Index.cshtml? If it is not it should be.
I am trying to learn MVC 3 & Razor and I'm stuck here for 3 hours now. This is what I have
MVC project created using the default template with Account registration and all that good stuff from the template. What I'm trying to do is have both registration page and login page in the index of the HomeController so I created a partial view for both Register (_RegisterPartial) and LogOn (_LogOnPartial). When I go to the index page, I see the registration and login forms which is good but when I try to login or register it goes into an infinite loop.
My HomeController looks like this;
// **************************************
// Registration
// **************************************
public ActionResult DoRegister()
{
return PartialView("_Register");
}
[HttpPost]
public ActionResult DoRegister(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email, model.UserProfile);
if (createStatus == MembershipCreateStatus.Success)
{
FormsService.SignIn(model.UserName, false); // createPersistentCookie
return View("Success");
}
else
{
ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
ViewBag.PasswordLength = MembershipService.MinPasswordLength;
return View(model);
}
// **************************************
// Login
// **************************************
public ActionResult DoLogin()
{
return PartialView("_Login");
}
[HttpPost]
public ActionResult DoLogin(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (MembershipService.ValidateUser(model.UserName, model.Password))
{
// logged in
FormsService.SignIn(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
Redirect(returnUrl);
}
else
{
View("Success");
}
}
else
{
// Not logged in
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View("Success");
}
and my cshtml looks like this;
#{
ViewBag.Title = "Home Page";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#if (Request.IsAuthenticated)
{
#Html.ActionLink("Log Off", "LogOff", "Account")
}
else
{
Html.RenderAction("DoLogin");
Html.RenderAction("DoRegister");
}
Regards,
Ryan
Do you read exception messages?
A public action method 'Register' was not found on controller 'AudioRage.Controllers.HomeController'
Now look at the code of HomeController you've posted. Do you see a Register action on it? I don't.
So add one:
public ActionResult Register()
{
...
}
In your HomeController you have an action called Register but action is only accessible through POST verbs as it is decorated with the [HttpPost] attribute:
[HttpPost]
[ActionName("Register")]
public ActionResult Index(RegisterModel model)
so you cannot invoke it with a GET verb on /Home/Register.
I can't exactly replicate your situation but I would say that you partial forms are not posting correctly. Have a look a rendered html of the page and check where the forms are being posted to. My guess is that they are being posted to the Index action. Coupled with the redirect, I think that is where the infinite loop is coming from.
My guess is the html rendered for both forms are similar and posting to the same action i.e. <form action="/" method="post">, since they are being rendered by the HomeController's Index action.
Change the partial forms (_Login.cshtml and _Register.cshtml) and explicitly state which action/controller combination to post to (more on Html.BeginForm from MSDN)
#using (Html.BeginForm("DoLogin","Home")) {/*snipped*/} //in _Login.cshtml
#using (Html.BeginForm("DoRegister","Home")) {/*snipped*/} //in _Register.cshtml
Also I would change the Html.RenderAction calls to
Html.RenderPartial("_Login");
Html.RenderPartial("_Register");