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.
Related
#using (Html.BeginForm("Orders1", "Track", FormMethod.Post))
{
#Html.TextBox("order")<br />
#Html.TextBox("order")
<input type="submit" value="Submit" />
}
Hello how can i use two text box and pass value to the same parameter? The first textbox work but the other textbox doesn't.
public ActionResult Orders1(IEnumerable<int> order)
{
var query = from a in context.CM_Checkout_Details
where a.CheckoutDetails_ID == order // my error
select a;
return View(query);
}
}
simple solution would be to change your parameter from int to IEnumerable<int>
public ActionResult Orders1(IEnumerable<int> orders)
{
}
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 have javascript blocks that are small. I would like to have these same blocks appear inline in my code but don't want to repeat them in each file. Is there a way that I can "include" code into the Razor file that doesn't involve
<script src="#Url.Content("~/Scripts/small_script_block1.js")" type="text/javascript"></script>
Thanks
Another possibility that will take me a few more minutes to write up:
Create an extension method for HtmlHelper. In your cshtml file it would look like this:
#Html.InlineScriptBlock("~/scripts/small_script_block1.js")
If you want I can send you the implementation but that idea might be all you need. If not, add a comment and I'll write it up.
EDIT CODE Below (not pretty and no warranty implied or given :)
public static class HtmlHelperExtensions
{
public static MvcHtmlString InlineScriptBlock<TModel>(this HtmlHelper<TModel> htmlHelper, string path)
{
var builder = new TagBuilder("script");
builder.Attributes.Add("type", "text/javascript");
var physicalPath = htmlHelper.ViewContext.RequestContext.HttpContext.Server.MapPath(path);
if (File.Exists(physicalPath))
{
builder.InnerHtml = File.ReadAllText(physicalPath);
}
return MvcHtmlString.Create(builder.ToString());
}
}
Keep in mind that if you drop this into your project you will need to make the namespace visible to the views. Unlike ASP.NET WebForms where you could provide markup at the top, Razor requires you to do this in the Web.config file in the Views folder.
<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="Your.Namespace.Here.Extensions" />
</namespaces>
</pages>
You can use the #RenderSection syntax.
<head>
#RenderSection( "JavaScript", optional : true)
</head>
somewhere in the body, add ..
#section JavaScript
{
<script src="/Scripts/script.js" type="text/javascript"></script>
}
EDIT:
Or if you prefer inline, then as follows:
#section JavaScript
{
<script type="text/javascript">
function doSomething() {
}
</script>
}
#RenderPage("_IncludeYourScriptsHere.cshtml")
Create a partial view and paste in your tag.
If any one searching for asp.net core. Here is the full conversion code to use in asp.net core
in razor file, use
#using Project.Utility
#Html.InlineScriptBlock("scripts/small_script_block1.js")
In utility extension
public static string GetString(IHtmlContent content)
{
var writer = new System.IO.StringWriter();
content.WriteTo(writer, HtmlEncoder.Default);
return writer.ToString();
}
public static HtmlString InlineStyleBlock(this IHtmlHelper helper, string path)
{
var builder = new TagBuilder("style");
builder.Attributes.Add("type", "text/css");
var physicalPath = "wwwroot/" + path;
if (File.Exists(physicalPath))
{
builder.InnerHtml.AppendHtml(File.ReadAllText(physicalPath));
}
return new HtmlString(GetString(builder));
}
public static HtmlString InlineScriptBlock(this IHtmlHelper helper, string path)
{
var builder = new TagBuilder("script");
builder.Attributes.Add("type", "text/javascript");
var physicalPath = "wwwroot/" + path;
if (File.Exists(physicalPath))
{
builder.InnerHtml.AppendHtml(File.ReadAllText(physicalPath));
}
return new HtmlString(GetString(builder));
}
this should embed or inline css/js in razor page/ html body. Works for dot net core
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>
Repository
namespace MvcApplication1.Models
{
public class GroupRepository
{
EgovtDataContext db = new EgovtDataContext();
public IQueryable<Group> FindAllGroups()
{
return db.Groups;
}
public IQueryable<Group> FindGroups()
{
return from Group in FindAllGroups()
orderby Group
select Group;
}
public Group GetGroups(int id)
{
return db.Groups.SingleOrDefault(d => d.int_GroupId == id);
}
//
public void Add(Group group)
{
db.Groups.InsertOnSubmit(group);
}
public void Delete(Group group)
{
db.Groups.DeleteOnSubmit(group);
}
//
// Persistence
public void Save()
{
db.SubmitChanges();
}
}
}
CONTROLLER
public ActionResult Index()
{
GroupRepository grouprepository = new GroupRepository();
ViewData["Group"] = grouprepository.FindGroups();
return View();
}
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage" %>
<% foreach (Group i in ViewData["Group"] as List<Group>)
{ %>
<input type="checkbox" name="Inhoud"
value="<%= i.int_GroupId %>" checked="checked" />
<% } %>
The thing is that it is not able to find group id and displaying the following error. What is the solution?
CS1061: 'System.Text.RegularExpressions.Group' does not contain a definition
for 'int_GroupId' and no extension method 'int_GroupId' accepting a first
argument of type 'System.Text.RegularExpressions.Group' could be found
(are you missing a using directive or an assembly reference?)
try using the namespace of the type your FindGroups() uses like so:
<% foreach (var i in ViewData["Group"] as List<MyNamespace.Blah.Group>)
{ %>
<input type="checkbox" name="Inhoud"
value="<%= i.int_GroupId %>" checked="checked" />
<% } %>
or add a namespace reference to your Web.Config or add the namespace to your page header. I think you will still have a namespace conflict with `System.Text.RegularExpressions'.
MVC Style Look with LINQ
(ViewData["Group"] as List<MyNamespace.Blah.Group>)
.ForEach(g => Response.Write(
Html.CheckBox("Inhoud", true, new { value = g.int_GroupId })));
Include your namespace for your Group class to your web.config pages/namespaces
<pages>
<namespaces>
...
<add namespace="Com.Example.Foo.Interfaces" />
<add namespace="Com.Example.Foo.Common" />
...
</namespaces>
</pages
Use a view-specific model instead of generic ViewData and pass Groups as a property of the model so it can properly determine the type.
using Com.Example.Foo.Interfaces;
using Com.Example.Foo.Common;
public class GroupModel
{
public IEnumerable<Group> Groups { get; set; }
}
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<GroupModel>" %>
<% foreach (var i in Model.Groups)
{ %>
<input type="checkbox" name="Inhoud"
value="<%= i.int_GroupId %>" checked="checked" />
<% } %>
I think you are having a reference problem, the code in the aspx believes you are talking about System.Text.RegularExpressions.Group rather than the type of Group you are returning from your ActionResult, where you use Group you will need to make sure it is the Group you want, either remove the using for the System.Text.RegularExpressions namespace, or if you need that, fully qualify Group with your namespace
Correct me if I am wrong, but it looks like this may be a namespace issue.
Group is in the scope of System.Text.RegularExpressions.Group, and I am guessing you have a table in your repos that is named Group. Try putting the namespace in for the type declaration in your forloop, that is of your repos so it doesnt confuse it with the System.Text.RegularExpressions.Group namespace.