I have these routes defined:
routes.MapRoute("CategoryList_CountryLanguage", "Categories/{id}/{urlCategoryName}/{country}/{language}",
new {
controller = "Categories",
action = "Details",
});
routes.MapRoute("CategoryList", "Categories/{id}/{urlCategoryName}",
new {
controller = "Categories",
action = "Details",
country = "US",
language = "EN"
});
and I'm generating links using:
#Html.ActionLink("desc", "Details", "Categories", new { id = item.Id, urlCategoryName = item.UrlFriendlyName}, null)
and the generated urls are in the form:
/Categories/id/friendly-name
I want to generate:
/Categories/id/friendly-name/US/EN
without having to specify the country and language in the ActionLink call, can't I use defaults like that?
The easy workaround is to specify those parameters in the ActionLink calls, but I would like to avoid that if possible. My hope is that the first route expects the values specified in the url, while the second has the defaults when not included in the url and would use that to create new urls, no luck so far, is this possible?
You can create a helper class called UrlHelpers.cs that looks like this:
public static class URLHelpers {
public static string CategoryList(this UrlHelper helper, int id, string urlFirendlyName) {
return CategoryList(helper, id, urlFirendlyName, "US", "EN");
}
public static string CategoryList(this UrlHelper helper, int id, string urlFirendlyName, string country, string language)
{
return helper.Action("Details", "Categories", new { id, urlCategoryName = urlFriendlyName, country, language });
}
}
Then in your view you would call it like this:
Some Text
Just a note: You will want to add the namespace of your helper to your web.config in the pages > namespaces section. So if you add a Helpers folder to the root of your MVC app and place the UrlHelper.cs class in it you would add:
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages"/>
<add namespace="MyProject.Helpers"/>
</namespaces>
</pages>
Related
The object 'YogaSpaceAccommodation' that I'm using as my type in GetEnumDescription seems to be brown and not found. Or something here isn't correct in terms of syntax.
<div id="AccomodationTypeSelector">
<select class="form-control" id="SpaceAccommodation" name="YogaSpaceAccommodation">
<option id="default">0</option>
#{
var accomodationValues = Enum.GetValues(typeof(YogaSpaceAccommodation));
foreach (var value in accomodationValues)
{
var index = (int)#value; var description = #EnumHelper.GetEnumDescription
<YogaSpaceAccommodation>(#index.ToString());
}
}
</select>
</div>
EnumDescription looks like this
public static string GetEnumDescription<T>(string value)
{
Type type = typeof(T);
var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();
if (name == null)
{
return string.Empty;
}
var field = type.GetField(name);
var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
}
Find out which namespace your enum is in and add a using declaration at the top of the View. Say your namespace is MyApp.Data.Enums you would add:
#using MyApp.Data.Enums
to the top of the view by the #model declaration. You can also add the namespace through the web.config located in your views folder:
<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="MyApp.Data.Enums" />
</namespaces>
</pages>
</system.web.webPages.razor>
Note that when you make these changes you usually have to close and reopen the views for intellisense to catch up. You may need the namespace of the helper functions you are using.
I have an issue on custom html helper method. I have added two custom html helper method. First method is MyTextBox and second one is MySelectBox Method which is extention to the HtmlHelper class.The following code is working fine.
C# :
namespace MyHtmlHelper
{
public static class HtmlHelperClass
{
public static MvcHtmlString MyTextBox(string fieldName)
{
return new MvcHtmlString("<input type=\"text\" name=\"" + fieldName + "\"></input>");
}
}
}
namespace MyHtmlHelper
{
public static class HtmlHelperExtension
{
public static MvcHtmlString MySelectBox(this HtmlHelper helper, string text)
{
return new MvcHtmlString("<select ><option>" + text + "</option></select>");
}
}
}
view:
#using MyHtmlHelper
<div>
#MyHtmlHelper.HtmlHelperClass.MyTextBox("test")
#Html.MySelectBox("Test")
</div>
I want this html helper method for all views in my application.so i removed MyHtmlHelper namespace from view and added in web.cong as follows
Web.config :
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
<add namespace="MyHtmlHelper"/>
</namespaces>
</pages>
My Problem is : MyTextBox helper method working fine but html extension method (MySelectBox) is not working.Anyone please help me ,what mistake i have done or how to resolve this issue?
There is a another webconfig in the view folder. You have to use this.
In my web.config I have the following:
<appSettings>
<add key="webpages:Enabled" value="false" />
<add key="authorizedUsers" value="jeff,jason,bob"/>
</appSettings>
In my _Layout.cshtml I have the following:
#{
List<String> authList = new List<string>();
authList = System.Web.Configuration.WebConfigurationManager.AppSettings["authorizedUsers"].Split(',').ToList();
if (authList.Any(u=>u == this.User.Identity.Name))
{
<li>#Html.ActionLink("Admin", "Index", "Admin")</li>
}
}
When I run this I get Object reference not set to an instance of an object. What do I need to do to get this to work?
My guess is you've put your setting in the wrong web.config. Double check you placed it in the appSettings section of the web.config located at project level and not the one located within the Views folder.
I’m stuck in a reference book by Steven Sanderson/Adum Freeman Pro ASP .Net MVC 3. I’ve made it up to page 185 where a HTML helper is to be used to return the numberer of pages in links. I found help on this site addressing my issue with this reference book, and walked through every step still having the same issues (link) MVC extension method error
When I run the code in a browser I get this error:
Compiler Error Message: CS1973: 'System.Web.Mvc.HtmlHelper'
has no applicable method named 'PageLinks' but appears to have an
extension method by that name. Extension methods cannot be dynamically
dispatched. Consider casting the dynamic arguments or calling the
extension method without the extension method syntax
The code builds fine but if I open any other class to edit this line of code to my helper method gets the same error as above.
#Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new {page = x}))
Helper Class:
namespace SportsStore.WebUI.HtmlHelpers
{
public static class PagingHelpers
{
public static MvcHtmlString PageLinks(this HtmlHelper html,
PagingInfo pagingInfo,
Func<int, string> pageURL)
{
StringBuilder results = new StringBuilder();
for (int i = 1; i <= pagingInfo.TotalPages; i++)
{
TagBuilder tag = new TagBuilder("a");
tag.MergeAttribute("href", pageURL(i));
tag.InnerHtml = i.ToString();
if (i == pagingInfo.CurrentPage)
tag.AddCssClass("selected");
results.Append(tag.ToString());
}
return MvcHtmlString.Create(results.ToString());
}
}
}
My View:
#{
ViewBag.Title = "Products";
}
#foreach (var p in Model.Products) {
<div class="item">
<h3>#p.Name</h3>
#p.Description
<h4>#p.Price.ToString("c")</h4>
</div>
}
<div class="pager">
#Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new {page = x}))
</div>
Web.config
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="SportsStore.WebUI.HtmlHelpers"/>
</namespaces>
</pages>
</system.web.webPages.razor>
You are passing a dynamic value to an extension method. (Hover over Model.PagingInfo and intellisense should tell you that the type is dynamic. This means it does not know what the type is until runtime) So, try changing your code so that it casts the dynamic type like this:
#Html.PageLinks((PagingInfo)Model.PagingInfo, x => Url.Action("List", new {page = x}))
You could fix this in two other ways:
As the error suggests, do not call it using the extension method:
PageLinks(Html, Model.PagingInfo, x => Url.Action("List", new {page = x}))
OR you could make the view know what the model is going to be so that it does not use a dynamic, by setting this at the top of your view
#model PagingInfo
Add #using project_name.HtmlHelpers
e.g.
#using ChristianSchool.HtmlHelpers
#Html.PageLinks(Model.PagingInfo, x => Url.Action("List", new { page = x, category = Model.CurrentCategory }))
you must add this lines in web.cofig under Views Folder not main one
<add namespace="YourProjectName.HtmlHelpers"/>
I tried to create this HtmlHelper method:
namespace Power.WebUx.Helpers
{
public static class HtmlHelperExtensions
{
public static MvcHtmlString SelectedIfMatch(this HtmlHelper helper, string actual, string expected)
{
if (expected == actual)
{
return new MvcHtmlString("<option selected=\"selected\" value=\"" + actual + "\"" + actual + "</option>");
}
else
{
return new MvcHtmlString("<option value=\"" + actual + "\"" + actual + "</option>");
}
}
I added the Power.WebUx.Helpers line to my web.config:
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
<add namespace="Power.WebUx.Helpers" />
</namespaces>
</pages>
However when I try to use the extension I get an error message saying that System.Web.Mvc.HtmlHelper does not contain a definition for SelectedIfMatch
Does the code I am trying to run look right or am I missing something?
Hope someone can see something obvious.
thanks
Jon Wylie
Import the namespace into your view to use any extension methods in that namespace
<%# Import Namespace =
"Power.WebUx.Helpers" %>
Make sure you're modifying the top level web.config file(instead of the one in the views folder), then close and open the files where you're trying to use the helper