Web API and View in same controller - asp.net-web-api

I'm creating a website that will have 50+ optical calculations. I need them accessible via api, but I also need them available in a view. I have a .dll that does the calculations that are accessed in a controller labeled with the name of the "type" of calculations. In this case it's a PrismController that handles all the calculations related to Prism. I'm only showing the Apical Angle calculation.
Is the way I'm doing it optimal in regards to best practices? Before I create 50 of these, I'd like to know if I'm going down the wrong path.
Seems like a lot of code.
The code in the view is what I'm using for one calculation.
[Produces("application/json")]
[Route("api/v1/[controller]")] <----------api route at controller level
public class PrismController : Controller
{
[HttpGet("ApicalAngle/{DegreesDeviation}/{Index}")]
public ActionResult<PrismModel> ApicalAngle(PrismModel prism)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
prism.Result = Prism.ApicalAngle(prism.DegreesDeviation, prism.Index);
return prism;
}
[Route("/[Controller]/[Action]")] <----view route overriding api route
[HttpGet("ApicalAngle")]
public IActionResult ApicalAngleCalc()
{
return View();
}
[HttpPost("ApicalAngle")]<------- Post that performs calculation
public ActionResult<PrismModel> ApicalAngleCalc(PrismModel prism)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var dev = prism.DegreesDeviation;
prism.Result = Prism.ApicalAngle(prism.DegreesDeviation, prism.Index);
return View(prism);
}

Related

mvc3 how can I reuse my actionResult code

Hello everyone as you can tell my still learning, I was wondering how or what is the best method to use in order to reuse my code for database actions ;for instance with the code below
// i reuse this code multiple times throughout my site but everytime I change it I must change
// all of the different Edit's each time I would like a central hub for all of it.
[Authorize]
public ActionResult Edit()
{
var ss = User.Identity.Name;
int myid = Convert.ToInt32(ss);
var buyer = (from s in db.buyers where myid == s.RegistrationID select s).FirstOrDefault();
ViewBag.RegistrationID = myid;
if (buyer != null && buyer.RegistrationID == myid)
{
return View(buyer);
}
else
{
RedirectToAction("buyerrequire");
}
return View("buyerrequire");
}
How can I put such code into a reusable container? so that if I change something there it will change all over that website where that container is used, sortoff like a _Partial except for ActionResults ... thanks for the help..
There are multiple ways of doing that.
1. You can have another base Controller for this purpose as follows:
public class SomeController : Controller{
// the code you use in multiple places.
}
Then the controllers which need these code, can extend this Controller.
You can have an [Attribute] for this functionality and you can decorate the methods with this attribute.
I would go for 2, this is also what asp.net mvc uses for common code such as attributes, logging, security etc.

static content pages in an MVC web application

I have just created my first MVC 3 project for a database search using EF db first, but the search is only a part of a big website most of the pages will just contain some text and images.
My question is basically about these pages which on the website would be .aspx, and the code behind would have nothing at all.
They use a master page and some user controls - my guess is that's the reason our front end person made them aspx not html.
I need to convert/include her pages into my project (I don't want to go back to stored procedures and listview after having used EF and Linq, plus I don't have time).
I know of one possible way: create a controller for each of the main menu items, then add ActionResult named for each of the submenu items returning View(), then create respective views.
public class LearnAboutStandardsController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult ITSStandardsBackground()
{
return View();
}
public ActionResult ResearchInitiatives()
{
return View();
}
So my static content pages will become Views.
It's working, I just want to do it for the rest of the pages and modify the links in the text of these pages.
Is there any other way to handle these pages?
There is no logic behind these pages.
I know this was not a perfect project for the MVC pattern with so much static content, but I had my reasons for it.
I handle this with an "StaticContent" controller:
StaticContentController.cs
public class StaticContentController : Controller
{
public ActionResult About()
{
return View();
}
public ActionResult Services()
{
return View();
}
public ActionResult Portfolio()
{
return View();
}
}
Add the code below your route config to handle the static routes:
routes.MapRoute(
"StaticContent",
"{action}",
new { controller = "StaticContent" },
new { action = "About|Services|Portfolio" } // Add more here
);
You're set.
If you need more pages just add the action in the StaticController and adjust your StaticContent MapRoute.
Personally, I would have controllers with simple actions that just render views. That way if you do add more features later you're already set up. And if you want to add security or caching it's a lot easier and more consistent.
You can still use WebForms (with the new Friendly URLs feature if you want "pretty" URLs) for the "static" pages. Or you can use Web Pages with Razor and create CSHTML files for the static content.

VS Express MVC3 newbie redirect issue

I'm brand new to MVC (having done classic ASP for many years). I'm not sure I know how to ask this question. Basically, I want the actions of one controller to seamlessly transfer/redirect to another view/controller. I have tried
public class SetupController : Controller
{
...
public ActionResult Bicycles()
{
return RedirectToAction("Index", "Bicycles");
}
}
but the problem is that this takes me to localhost/Bicycles (which doesn't exist). What I want is to go to localhost/Setup/Bicycles. I tried this (adding "Setup" parent folder to controller name):
public class SetupController : Controller
{
...
public ActionResult Bicycles()
{
return RedirectToAction("Index", "Setup/Bicycles");
}
}
but this created an infinite redirect loop, which the browser rightly refused to do.
Hope it makes sense what I'm trying to do.
I believe what you are looking for is:
public ActionResult Bicycles()
{
return RedirectToAction("Bicycles", "Setup");
}
The first parameter is the Action, the second the Controller.
Since you already are in SetupController in Bicycles action, you would get an infinite redirect. However, from what you mentioned, that is where you are attempting to redirected to.
protected internal RedirectToRouteResult RedirectToAction(
string actionName,
string controllerName
)
So your first example redirects to Index action in Bicycles controller, hence the localhost/Bicycles.

why TempData[] doesnt work with IE

İn my MVC3 project, there is plenty of TempData[] that I am using for passing datas between actions. And it works totaly perfect when I use Chrome. But in IE I can't get values of TempData[] items. if anyone knows whats the problem and how can I solve it?`
public class SomeController : Controller
{
public ActionResult SomeAction()
{
TempData["id"] = "someData";
return View();
}
}
public class AnotherController : Controller
{
public ActionResult AnotherAction()
{
string data = Convert.ToString(TempData["id"]);
return View();
}
}
`
You should never return a view from a controller action that stores something into TempData. You should immediately redirect to the controller action that is supposed to use it:
public class SomeController : Controller
{
public ActionResult SomeAction()
{
TempData["id"] = "someData";
return Redirect("AnotherAction", "Another");
}
}
public class AnotherController : Controller
{
public ActionResult AnotherAction()
{
string data = Convert.ToString(TempData["id"]);
return View();
}
}
The reason for this is that TempData survives only for a single additional request. So for example if inside the view you are sending an AJAX request to some controller action (no matter which) and then have a link in this view pointing to the target action, when the user is redirected to this target action TempData will no longer exist since it was lost during the AJAX request done previously.
If you need to store data for longer than a single redirect you could use Session.
If you need to store data for longer than a single redirect you should use Keep or Peek methods.
string data = TempData["id"].;
TempData.Keep("id");
or simply use,
string data = TempData.Peek("id").ToString();
Peek function helps to read as well as advice MVC to maintain “TempData” for the subsequent request.

MVC Routes based on POST parameters

We have an a PHP application that we are converting to MVC. The goal is to have the application remain identical in terms of URLs and HTML (SEO and the like + PHP site is still being worked on). We have a booking process made of 3 views and in the current PHP site, all these view post back to the same URL, sending a hidden field to differentiate which page/step in the booking process is being sent back (data between pages is stored in state as the query is built up).
To replicate this in MVC, we could have a single action method that all 3 pages post to, with a single binder that only populates a portion of the model depending on which page it was posted from, and the controller looks at the model and decides what stage is next in the booking process. Or if this is possible (and this is my question), set up a route that can read the POST parameters and based on the values of the POST parameters, route to a differen action method.
As far as i understand there is no support for this in MVC routing as it stands (but i would love to be wrong on this), so where would i need to look at extending MVC in order to support this? (i think multiple action methods is cleaner somehow).
Your help would be much appreciated.
I have come upon two solutions, one devised by someone I work with and then another more elegant solution by me!
The first solution was to specify a class that extends MVcRouteHandler for the specified route. This route handler could examine the route in Form of the HttpContext, read the Form data and then update the RouteData in the RequestContext.
MapRoute(routes,
"Book",
"{locale}/book",
new { controller = "Reservation", action = "Index" }).RouteHandler = new ReservationRouteHandler();
The ReservationRouteHandler looks like this:
public class ReservationRouteHandler: MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var request = requestContext.HttpContext.Request;
// First attempt to match one of the posted tab types
var action = ReservationNavigationHandler.GetActionFromPostData(request);
requestContext.RouteData.Values["action"] = action.ActionName;
requestContext.RouteData.Values["viewStage"] = action.ViewStage;
return base.GetHttpHandler(requestContext);
}
The NavigationHandler actually does the job of looking in the form data but you get the idea.
This solution works, however, it feels a bit clunky and from looking at the controller class you would never know this was happening and wouldn't realise why en-gb/book would point to different methods, not to mention that this doesn't really feel that reusable.
A better solution is to have overloaded methods on the controller i.e. they are all called book in this case and then define your own custome ActionMethodSelectorAttribute. This is what the HttpPost Attribute derives from.
public class FormPostFilterAttribute : ActionMethodSelectorAttribute
{
private readonly string _elementId;
private readonly string _requiredValue;
public FormPostFilterAttribute(string elementId, string requiredValue)
{
_elementId = elementId;
_requiredValue = requiredValue;
}
public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
{
if (string.IsNullOrEmpty(controllerContext.HttpContext.Request.Form[_elementId]))
{
return false;
}
if (controllerContext.HttpContext.Request.Form[_elementId] != _requiredValue)
{
return false;
}
return true;
}
}
MVC calls this class when it tries to resolve the correct action method on a controller given a URL. We then declare the action methods as follows:
public ActionResult Book(HotelSummaryPostData hotelSummary)
{
return View("CustomerDetails");
}
[FormFieldFilter("stepID", "1")]
public ActionResult Book(YourDetailsPostData yourDetails, RequestedViewPostData requestedView)
{
return View(requestedView.RequestedView);
}
[FormFieldFilter("stepID", "2")]
public ActionResult Book(RoomDetailsPostData roomDetails, RequestedViewPostData requestedView)
{
return View(requestedView.RequestedView);
}
[HttpGet]
public ActionResult Book()
{
return View();
}
We have to define the hidden field stepID on the different pages so that when the forms on these pages post back to the common URL the SelectorAttributes correctly determines which action method to invoke. I was suprised that it correctly selects an action method when an identically named method exists with not attribute set, but also glad.
I haven't looked into whether you can stack these method selectors, i imagine that you can though which would make this a pretty damn cool feature in MVC.
I hope this answer is of some use to somebody other than me. :)

Resources