Can I share a view in asp.net mvc? - c#

My controller has 2 actions:
Results()
Index()
I want to share the view named index.aspx between these 2 actions.
See my previous post for more information
When I build my link to the page, I assume I cannot send it to Index action as it is expecting a FormCollection type and hence I create a Results action
public ActionResult Results(ClientSearch data, int? page)
{
FormCollection collection = new FormCollection();
collection.Add("FNAme", data.FName);
collection.Add("Lane", data.Lane);
collection.Add("Zip", data.Zip);
collection.Add("Phone", data.Phone);
return Index(page, collection);
}

Not sure I completely understand your question, but if you want to use the same View on different ActionResults, you can:
public ActionResult One() {
// do stuff
return View("Index", myModel);
}
public ActionResult Two() {
// do stuff
return View("Index", myOtherModel); // Same View
}
Just make sure you are providing the same Type for the View (if the View needs a Type at all).

Of course you can. It's up to controller to decide how to react and what view to serve back.
Now that I've read your question to the end :)), well, you can get away with two actions of the same name. The one will be accepting GET commands (initial load of the page), the other will be serving POST requests, perform the necessary action and redirect back to the same View.
public MyController
{
[AcceptVerbs (HttpVerbs.Get)]
public ActionResult Index ()
{
return View ();
}
[AcceptVerbs (HttpVerbs.Post)]
public ActionResult Index (ClientSearch data, int? page)
{
// Process form post
return RedirectToAction ("Index");
}
}

Related

View not found from controller

I return the View from my controller start_run1 to a view start_run1
public ActionResult start_run1(int? id) { ....
return(View);
}
I get 404 page not found, even if I try using absolute paths etc etc.
if I add the code it finds the page but model data or ViewBag data doesn't get passed.
public IActionResult start_run1()
{
return View();
}
I have another similar controller function which works without doing this.
Any ideas, Ive tried everything.

How do I create a GET form with validation in MVC

I'm having a real problem trying to articulate this seemly simple problem.
I have a single view that contains a FORM with a few search fields at the top of the view and the results of that search get shown on the same view after submitting the form.
I have a single HTTPGET controller method that takes the form fields as parameters and IF it was submitted by a user it will pass the model back to the view with the results to be shown and pre-populate the search form with what they filled out.
How can I tell if the page was loaded with default parameters vs. someone actually submitted the form.
What's the best way to accomplish this?
If I am understanding your question correctly then I think you need to consider the HttpGet attribute:
https://msdn.microsoft.com/en-us/library/system.web.mvc.httpgetattribute(v=vs.118).aspx
and the HttpPost attribute:
https://msdn.microsoft.com/en-us/library/system.web.mvc.httppostattribute(v=vs.118).aspx
Lets say you have a create method. The Http method would look like this:
[HttpGet]
public ActionResult Create()
{
}
and the post method would look like this:
[HttpPost]
public ActionResult Create(Person p)
{
//Logic to insert p into database. Could call an application service/repository to do this
}
RedirectToAction solve the problem.
you can go back to the get method after submited data and populate the view with default values
[HttpGet]
public ActionResult Create()
{
// fill model to default data
return view(model);
}
[HttpPost]
public ActionResult Create(Person p)
{
//do your stuff save data
return RedirectToAction("Create");
}
or
[HttpPost]
public ActionResult Create(Person p)
{
if(...)
{
//do your stuff any logic
return RedirectToAction("Create");
}
//do your stuff
return view(...);
}

All Views are not Loading in Browser

When I load the default page (http://localhost/MVCP/Home/index) it loads correctly, whereas when I load another view (http://localhost/MVCP/Home/Create) it doesn't load. How can I fix this?
My Create action in HomeController:
[HttpGet] [ActionName("Create")] public void Create() { }
Q: Do you have an action in your HomeController called Create?
A: Yes, [HttpGet] [ActionName("Create")] public void Create() { }
Your action return value is void and probably you even didn't write anything in response. change the signature of action to have an ActionResult as return a View.
public ActionResult Create()
{
return View();
}
To learn more:
Adding a View
in Getting Started with ASP.NET MVC 5 Series.
May be there is no view you have created so far and it seems your controller are inside area folder so have u checked your routeing too.
I think your Action should return ActionResult or ViewResult but certainly not "void" as you have written currently.
and also you should write
return view();
in Create action

Call controller from another controller and return a view

I call an Action from a Login controller to authenticate users, once the user is authenticated I would like to call either the Cashier or the Supervisor action, depending on the user's role, and display the appropriate view.
I can break on AuthenticateUserByCard but RedirectToAction doesn't seem to be working.
I'm not sure if what I'm trying to do is deviating from the MVC architecture, if so please suggest the correct way to do this
Login controller:
public class LoginController : Controller
{
public ViewResult Index()
{
return View();
}
[HttpPost]
public ActionResult AuthenticateUserByCard(string token)
{
//Authenticate user and redirect to a specific view based on the user role
Role role = GetRoleByToken(token);
if(role.UserType == UserType.Supervisor)
return RedirectToAction("Supervisor", "Login", new { id = token });
else
return RedirectToAction("Cashier", "Login", new { id = token });
return null;
}
public ActionResult Supervisor(string id)
{
//Do some processing and display the Supervisor View
return View();
}
public ActionResult Cashier(string id)
{
//Do some processing and display the Cashier View
return View();
}
}
Java Script:
$.get("/Login/AuthenticateUserByCard",{token:token});
jQuery post and get ignore 301 browser redirects returned from the server. You would normally need to handle them yourself. This can get messy: How to manage a redirect request after a jQuery Ajax call
All you really need in this case is to return the choice of methods, but make them return explicit views (not implicit). The default would always be to return the view based on the IIS-called method i.e. "AuthenticateUserByCard" unless you specify the view.
e.g.
public class LoginController : Controller
{
public ViewResult Index()
{
return View();
}
[HttpPost]
public ActionResult AuthenticateUserByCard(string token)
{
//Authenticate user and redirect to a specific view based on the user role
Role role = GetRoleByToken(token);
if(role.UserType == UserType.Supervisor)
return Supervisor(token);
else
return Cashier(token);
return null;
}
public ActionResult Supervisor(string id)
{
//Do some processing and display the Supervisor View
return View("Supervisor");
}
public ActionResult Cashier(string id)
{
//Do some processing and display the Cashier View
return View("Cashier");
}
This will not change the URL though. If you need that too try the other answer I linked. You basically handle the redirect in jQuery and goto the new page.
Alternatively, to change the URL, put the desired URL into a hidden field of the returned views and extract that value to update the browser URL (just a thought) :)

How to use RedirectToAction while passing view model to a view with different route

I have a ASP.NET MVC 3 app with a common scenario where there is with an "About" controller using "Contact" and "ThankYou" actions.
I want user to go to /about/contact, fill out the form, submit it, and be taken to /about/contact/thankyou * page where the form contents (aka view model) will be displayed.
** Note there is no "Contact" controller nor do I want to create one for this purpose if possible.*
I am using RedirectToAction to prevent resubmission (Post/Redirect/Get pattern) and TempData to pass on view model to thank you page.
I can also use TempData to check if thank you page was reached directly and redirect back to contact form page (so it would not register as a "goal" in web analytics)
But one thing I could not figure out is how to use different route for thank you page so it appears as /about/contact/thankyou
Am I doing this right?
Is there a better way?
Here are relevant actions in AboutController
<!-- language: c# -->
[RequireHttps]
public ActionResult Contact()
{
var viewModel = new ContactViewModel();
return View(viewModel);
}
[RequireHttps]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Contact(ContactViewModel viewModel)
{
if (!ModelState.IsValid)
{
return View(viewModel);
}
// not sure if this is the best way or how to redirect to /contact/thankyou
TempData["viewModel"] = viewModel;
return RedirectToAction("ThankYou");
}
[RequireHttps]
public ActionResult ThankYou()
{
var viewModel = TempData["viewModel"];
// upon direct access, viewModel will be null and missing, so redirect to Contact form
if (viewModel == null)
{
return RedirectToAction("Contact");
}
return View(viewModel);
}
You could define a custom route before the default route:
routes.MapRoute(
"contact",
"about/contact/thankyou",
new { controller = "About", action = "ThankYou" }
);
Now when you navigate to /about/contact the Contact GET action will be executed (You have to rename it as in your code it is called ContactUs). Then the user fills the form and submits to the Contact POST action. The url stays the same for the moment: /about/contact. After the redirect the ThankYou action is executed and the url changes to /about/contact/thankyou.

Categories

Resources