MVC Helper class access in View - asp.net-mvc-3

I have created a detailpage.cshtml file in App_code
#helper convertTime(DateTime value)
{
value.ToString("dd/MM/yyyy");
}
and am trying to access this in my view but am not able to access this in my view.
Am i missing something ?
i referred http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx but still am not getting what i am missing ?

Related

Is it possible to RenderPartial a default or error View if the specified View is not found?

I am using MVC3.
I am wondering whether it is possible to render an error View if the specified View is absent.
ie if "MyTableX" is absent:
RenderPartial("MyTableX");
would return "Error.cshtml" as the Partial View, saying something like "Partial View not found" in the page.
MVC got an attribute called [HandleError] which you should set on your BaseController (or on each controller). There is no need to specify any of the options for the attribute.
The problem with [HandleError] is that it can’t handle 404 (not found), thus we need to create a custom error controller and tell ASP.NET to use it (by configuring web.config and creating and ErrorController):
http://blog.gauffin.org/2011/11/how-to-handle-errors-in-asp-net-mvc/#.UTknoxyfjmA
You can do something based off of this - the trick is in getting the view path.
A missing view returns an InvalidOperationException. So we really need to determine if the view is missing or if it's caused from something different. One way is to figure out how to get the IView in the filter, cast it to a RazorView and grab the path off of it - or the 'hacky' way is to do the below code, but actually look for "the view" and "was not found" in the exceptions message. Its ugly, I know, but if you want something that works tonight, thats all I got before I head to bed, otherwise try to get the view info from that filter.
This code from Phil Haack in this link may help in trying to get the path name, a quick test yielded I wasn't able to get the IView because my filterContext.ParentActionViewContext was null.
Retrieve the current view name in ASP.NET MVC?
So I wrote this basic one, but again, anything throwing an InvalidOperationException will cause this.
Also note a missing 'MissingView.cshtml" could cause an infinite loop here (untested assumption)
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class ViewCheckFilterAttribute : FilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
var exception = filterContext.Exception;
if (exception is System.InvalidOperationException)
{
//ideally here we check to ensure view doesn't exist as opposed
//to something else raising this exception
filterContext.Result = new ViewResult
{
ViewName = "~/Views/Shared/MissingView.cshtml"
};
filterContext.ExceptionHandled = true;
}
}
}

MVC3 URL Parameters

I have some parameters in URL, which I would like to be present in the URL for all pages in my MVC3 app. For example:
mycompany.com/home?param=1
mycompany.com/cart?param=1
mycompany.com/logout?param=1
Whether the user is navigating to a new page or submitting a form, how can I have my parameter
be present in all my pages? Right now the only way I can think off is somehow reconstruct the URL for every new view I need to render. Is there built in functionality in MVC to do this?
Thanks
That sounds like something you should store in Session instead of updating all of your links to add the same parameter.
You could use a Session variable as the other poster suggested, or you could use a base view model which holds this static param value.
So your base view would be something like this:
public class BaseViewModel
{
public static int ParamValue = 1;
}
then in each view model you use for each view, you'd have something like this:
public class PageViewModel : BaseViewModel
{
// properties
}
This way, in each view, you can just reference #Model.ParamValue whenever you need to access it:
#Model Namespace.PageViewModel
My param value is <b>#Model.ParamValue</b>

MVC3 Routing Issues - How to re-use a View for all Controller Methods?

I'm trying to implement a common controller in MVC3 to return various JSON feeds, example -
public class AjaxController : Controller
{
public ActionResult Feed1()
{
ViewBag.Json = LogicFacade.GetFeed1Json();
return View();
}
public ActionResult Feed2()
{
ViewBag.Json = LogicFacade.GetFeed2Json();
return View();
}
}
This class has 30+ methods in it, the problem is this requires implementing an IDENTICAL View for each of the Controller's methods (sigh) that writes out ViewBag.Json.
I'm assuming this is a routing issue but I'm struggling with that. The following didn't work -
Tried setting ViewBag.Json then using RedirectToAction() but that seems to reset ViewBag.Json.
Note JsonResult is not appropriate for my needs, I'm using a different JSON serialiser.
So the objective here is to maintain one View file but keep this class with seperate methods that are called by routing, and not a crappy switch statement implementation.
Any help appreciated.
Use the same view and just specify the name. You can store in the controller's view folder, if only used by one controller, or in the Shared view folder if used by more than one.
return View("SharedJsonView");
Another, perhaps better, solution would be to create your own result -- maybe deriving from JsonResult, maybe directly from ActionResult -- that creates the JSON response that you need. Look at the source code for JsonResult on http://www.codeplex.com/aspnet for ideas on how to do it.

MVC3 load controller in a View

I am trying to load a page and in that view i want to load another view from a different controller which retrieves information.
I can use:
#Html.Partial("otherView")
which works for pages which require no data but i would like the page to retrieve data, so using :
#Html.Action("otherView")
i thought should work but does not and i get an HttpException
"Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'."
There must be a way of doing this,
Thanks
Kelv
use
#Html.Action("otherView", "otherController", new { vm = viewModel })
and in the controller create an action
public ActionResult otherView(otherViewModel vm)
{
return PartialView("otherView", vm);
}
Sounds like you're looking for RenderAction.
Here's the first article I found on the subject.

Weird behavior of urlrewriting in MVC3 with razor viewengine

I am working on a project which adopted ASP.NET MVC3(Razor) tech.
Now, I have a controller below:
public class Home: Controller
{
public ActionResult Result(string id)
{
return View(id);
}
}
and I have set MapRoute as below:
context.MapRoute(
"Home_result",
"Home/Result/{id}",
new { controller="Home", action = "Result"}
);
and it was suposed to display a View which named "Result" when I typed the url http://domain.com/Home/Result/abc123 in the browser. However it didn't.
Instead it gave me an exception below:
The view 'Result' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/Home/abc123.cshtml
~/Views/Home/abc123.vbhtml
~/Views/Shared/abc123.cshtml
~/Views/Shared/abc123.vbhtml
It is strange isn't it?
Can anyone help me to figure out what mistakes I've made?
return View(id);
Returns a view with the name of ID's value (.cshtml), not the view with the name result.cshtml. I think this is because Id is a string. Are you trying to pass the id to the view?
To return the view matching the name of your controller's action simply use
return View();
If you want to pass that value to the view, for what ever crazy reason, using the viewbag is the easiest way since the string id is being used to declare a view name.
ViewBag.ID = id;
return View();
Then in the view just use the value you stored. And yes Razor HTML encodes by default.
#ViewBag.ID

Resources