Entering to index page? - asp.net-mvc

//
// Post: /Search/Alternativ1/txtBoxTitle)
[HttpPost]
public ActionResult Alternativ1(int txtBoxTitle)
{
SokningMedAlternativ1 test= new SokningMedAlternativ1();
if (txtBoxTitel != null)
{
var codeModel = test.FilteraBokLista(txtBoxTitel);
}
return View(codeModel);
}
Problem:
I have problem to find a solution to go back to my index page (first page when entering a website for the first time) view if txtBoxTitle has null.
My request:
How shall I enter to my index page view automatically if txtBoxTitle contains null?

You have two possibilities:
Redirect to the Index action (sending a 302 status code to the client):
return RedirectToAction("Index");
Render the Index view (the client keeps the original URL in the address bar, no redirect here):
return View("Index", someModelThatTheIndexActionExpects);
If this Index action is located on another controller you have the possibility to specify this controller name:
return RedirectToAction("Index", "Home");
and:
return View("~/Views/Home/Index.aspx", someModelThatTheIndexActionExpects);
Remark: In your example the txtBoxTitle argument is declared as System.Int32, so talking about it being or not being null just makes absolutely no sense as this is a value type which can never be null and your if condition code won't even compile as you have it currently written.

Related

mvc Remove url page name from response redirect

I have read a lot of post telling how to remove Controller an Action from Url
My case is simplest but do not haw to do it.
When Start, it execute Home Controller for default. Depending Active Directory conditions I have to redirect to certain standard HTML. It could be
Response.Redirect("Page1.html");
Response.Redirect("Page2.html");
Response.Redirect("Page3.html");
It will show
Localhost:4000/Page1.html or
Localhost:4000/Page2.html or
Localhost:4000/Page3.html
What i need is to show only
Localhost:4000
thanks
you may want to write a specific action like this
so first lets say your route config is intact and default rouute is being used then in home controller change its index like ths
public ActionResult Index()
{
if(Your condition)
{
return new FilePathResult($"~/Views/Page1.html.html", "text/html");
}
if(Your condition2)
{
return new FilePathResult($"~/Views/Page2.html", "text/html");
}
if(Your condition3)
{
return new FilePathResult($"~/Views/Page3.html", "text/html");
}
}

mvc ActionResult is not return to anotherView

Here I have two methods.
Login method
public ActionResult Login(LoginCrediential ObjCrendentials)
{
if (x == true)
return RedirectToAction("RoutingAction");
else
return View("Index");
}
RoutingAction method
public ActionResult RoutingAction()
{
if (User.IsInRole("Admin"))
return View("Admin/AdminHome/index");
else if (User.IsInRole("Hr"))
return View();
else
return View();
}
When my if condition Is true in the Login method, its navigating to RoutingAction() but throwing the following error
Admin/AdminHome/index or its master was not found or no view engine supports the searched locations
In url its showing as http://localhost:3013/Home/RoutingAction
Please help me how I can solve this issue.
Well, It's only going to search the Views folder of your controller (Home) and the Shared views. However, you should be able to specify the full path to the View:
return View("~/Areas/Admin/Views/AdminHome/Index.cshtml");
But, if you want the url to reflect this location, then you probably need to have an AdminHome Controller and redirect to its index action.

How can I set the ReturnUrl when I am using RedirectToAction?

I have a controller that redirects to another action, e.g.
mysite.com/food/3
This action does a RedirectToAction to an action called Cake and passes in id=3.
If the user is not authenticated at that point, you go back to the loginpage, but the RedirectUrl is /Cake (without any mention of the id) and not /food/3. This causes an error once you log in because firstly it shouldn't be accessed via that url in the browser, and secondly because the parameters have vanished.
Is there a simple way to make sure it redirects to the original URL in the browser, or do I have to write a custom authorize attribute and store a lookup table to get the parent page?
Gonna take a stab at this one.
Food and Cake take id values and redirect parameters and just pass them around freely where they can be used as you see fit.
Food
public ActionResult Food (int id, string returnUrl = string.Empty)
{
// Do work
return RedirectionToAction("Cake", new { id, returnUrl })
}
Cake
[Authorize]
Cake (int id, string returnUrl = string.Empty)
{
// Do work
if (returnUrl != string.Empty)
return Redirect (returnUrl);
return View();
}
A problem arises when a View is finally returned to the client because then you have to somehow get that returnUrl into the form posted when they submit their login info because you want to use it later. So the first step is getting it into the View's form so it's included in the model that gets posted. One way to do that is the ViewBag; another way is pulling it from the query string. I've shown an example of both below.
Option 1:
Login
Login (string returnUrl = string.Empty)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
Login.cshtml
Model.ReturnUrl = ViewBag.ReturnUrl;
Option 2:
Login
Login ()
{
return View();
}
Login.cshtml
Model.ReturnUrl = Request.QueryString["ReturnUrl"];
If this doesn't suffice, comment and I can try to modify this answer further.
The simplest way to make this work is to put the AuthorizeAttribute onto the action method that calls RedirectToAction to short circuit the nonsense of building the wrong URL. The FormsAuthenticationModule uses the RawUrl of the request when it adds the ReturnUrl parameter, so it not possible to modify without building your own custom FormsAuthenticationModule (which you could consider option B). But if you check authorization before you redirect the RawUrl will be correct.
// This ensures it builds the correct ReturnUrl.
[Authorize]
public ActionResult Food (int id)
{
// Do work
return RedirectionToAction("Cake", new { id = id })
}
// This ensures the final destination cannot be accessed
// without authorization.
[Authorize]
public ActionResult Cake (int id)
{
// Do work
return View();
}

What Views can a Controller Action return?

In ASP.NET MVC 5, does every Controller Action have to return a View with the same name as the Controller?
Here's my project. Have a webpage which contains a button to upload an image to a database. When the webpage is loaded, I want it to display a list of all the images that have already been uploaded. So, the Index (default) Action for this Controller loads the images from the database, and returns the Index View, which in turn displays the list of images:
public ActionResult Index()
{
// Load the images from the database
var images = GetImages();
return View(images);
}
On that same webpage, there is a button which allows the user to upload an image to the database. That button calls the Upload Action, which uploads the file based upon the "file" and "folder" arguments that are passed, and then finally returns the Index View again:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, string folder)
{
// Upload the file from the specified folder
// ...
// ...
// ...
return Index();
}
However, when a user clicks on this upload button, the following error message is displayed:
The view 'Upload' or its master was not found or no view engine supports the searched locations
But I am not trying to render a View called "Upload" - I am trying to render the view called "Index", which is why I have the line return Index();.
Any help on where I'm going wrong?
Answer
Although Vitaliy and Nathan A provided adequate answers, I wanted to explain why your initial approach doesn't work because it's a great question and doesn't seem to make sense.
To get our answer we have to look at the ASP.NET MVC source code.
Before we get to that let's walk through your code.
The user visits (or POSTS to) /Controller/Upload
We do some logic and then return Index()
Index() is a method that returns its own view with its own model
MVC fails to find 'Upload' view and throws an exception
What went wrong?
Firstly know that Index() is being called and returned successfully. The model object is also being passed to the view (if one is found).
When you return Index(), it is returning View() which is an inherited method from the Controller class which returns a ViewResult.
A ViewResult inherits from ViewResultBase.
When a ViewResult is being returned it calls ExecuteResult().
Taking a look at the source code for ExecuteResult():
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (string.IsNullOrEmpty(this.ViewName))
{
this.ViewName = context.RouteData.GetRequiredString("action");
}
ViewEngineResult viewEngineResult = null;
if (this.View == null)
{
viewEngineResult = this.FindView(context);
this.View = viewEngineResult.View;
}
TextWriter output = context.HttpContext.Response.Output;
ViewContext viewContext = new ViewContext(context, this.View, this.ViewData, this.TempData, output);
this.View.Render(viewContext, output);
if (viewEngineResult != null)
{
viewEngineResult.ViewEngine.ReleaseView(context, this.View);
}
}
The key here is context.RouteData.GetRequiredString("action"). This code gets the action name so that a view can be found and rendered. Note that it is using a ControllerContext.
Because of this, your action is actually set when the Upload() method is first called. If you step through your Index() method you will see that calling context.RouteData.GetRequiredString("action") will return the string "Upload".
This is because, within the context of the user request, the action is in fact Upload (that's the page they requested).
Fun fact
If you return Index() and that method happens to alter the ViewBag (ViewData) then the ViewData will be altered regardless of what is rendered.
If your Upload() does this:
ViewBag.Test = "Upload method";
And you return Index() and your Index() does this:
ViewBag.Test = "Index method";
Then the value of Test will be "Index method".
Look up the documentation on the View method. It has several arguments you can provide, one of them being a string of the name of the view, but you always use the View() method if you want to return a view.
However, if you don't want to use the default View name (being the name of the action method), simply use a string to specify a new name like so:
public ActionResult Upload(HttpPostedFileBase file, string folder)
{
return View("Index");
}
you can do either:
return RedirectToAction("Index");
or:
return View("Index");
Just a side-note, you're not constrained to show views from the View folder for the controller name. You can do
public ActionResult something()
{
return View("../OtherView/somethingElse");
}

Pass Value from View To Controller in Asp.net MVC

I am trying to pass a message to another view (actually same controller) I can do it well but there is a problem for me..
I am new on web and it doesnt seem good ..
and here my c# code
if (createStatus == MembershipCreateStatus.Success)
{
string registrationMessage = "You have registered successfully";
return RedirectToAction("KurumsalGiris", new { message = registrationMessage });
}
[AllowAnonymous] //sonradan eklendi
public ActionResult KurumsalGiris(string message="")
{
if (User.Identity.IsAuthenticated)
return Content("Zaten giriş yapmışsınız");
ViewBag.RegistrationMessage = message;
return View();
}
and here html side
#model E_Cv.Models.LogOnModel
#{
ViewBag.Title = "Kurumsal Giriş";
}
<h2>Kurumsal Giriş</h2>
<h2>#ViewBag.RegistrationMessage</h2>
<p>
Please enter your user name and password.
#Html.ActionLink("Yeni Kurum Kaydı", "KurumsalKayit")
if you don't have an account.
</p>
so I dont know how to pass value to another view with different way.. I dont want to show this kind of message on address bar and user musnt change it.
Secondly Could I do it with "Get" Method?
Why don't you just return a different view rather than redirecting? In fact, the code the posted in the first place should be posting to a controller that returns a view for a successful login.
In fact, why are you redirecting to a page that asks the user to login if they've just logged in?
Other possible options include encrypting the string in the URL, or just passing a flag in the URL that the controller translates into the corresponding string.
What you would do is instead of returning a RedirectToAction
you could return the View directly: (second parameter is a model, where you can use the same model class E_Cv.Models.LogOnModel adding a RegistrationMessage property to it)
return View("<name of the view>",
new E_Cv.Models.LogOnModel {
RegistrationMessage = "You have registered successfully"
});
or keep the data in the ViewBag like you have done:
ViewBag.RegistrationMessage = "You have registered successfully";
return View("<name of the view>");
regarding your last question, give the message is showing in your URL, you are using the GET method, if you return a View instead of a redirect, it'll avoid showing anything in the URL
You should use TempData in this scenario
if (createStatus == MembershipCreateStatus.Success)
{
TempData["Message"] = "You have registered successfully";
return RedirectToAction("KurumsalGiris");
}
And then in your view
#if (TempData["Message"] != null)
{
<h2>#TempData["Message"]</h2>
}
Or if you want to do it in the controller, just keep your view the same as it is at the moment and set ViewBag.RegistrationMessage in the controller
ViewBag.RegistrationMessage = TempData["Message"];
If the question is how to pass data between controllers without using the querystring, then one option is the Session object.
if (createStatus == MembershipCreateStatus.Success)
{
Session["Message"] = "You have registered successfully";
return RedirectToAction("KurumsalGiris");
}
[AllowAnonymous] //sonradan eklendi
public ActionResult KurumsalGiris(string message="")
{
if (User.Identity.IsAuthenticated)
return Content("Zaten giriş yapmışsınız");
ViewBag.RegistrationMessage = (string) Session["Message"];
return View();
}
However, I agree with #Jonathan Wood below that this is not necessarily the best approach to the particular problem you are attempting to solve. Still, as a general technique, it is worth knowing about.

Resources