I have a model for a drop down menu similar to this one. I am trying to create a controller for it.
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View(new MyData());
}
And I create my View like this
#Html.DropDownListFor(m => m.State,
new SelectList(Model.StateList, "Value", "Text"))
But I am receiving the error below for the line above:
Compiler Error Message: CS1061: 'System.Collections.Generic.List<Projects.Models.MyData>' does not contain a definition for 'StateList' and no extension method 'StateList' accepting a first argument of type 'System.Collections.Generic.List<Projects.Models.MyData>' could be found (are you missing a using directive or an assembly reference?)
Can you please direct me what I am doing wrong?
the problem is #model List<ProjectName.Models.MyData>
simply change it to
#model Projects.Models.MyData
cheers!
I would like to use custom #Html.ActionLink
I am trying to use the following code:-
public static class LinkExtensions
{
public static MvcHtmlString MyActionLink(
this HtmlHelper htmlHelper,
string linkText,
string action,
string controller)
{
var currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
var currentController = mlHelper.ViewContext.RouteData.GetRequiredString("controller");
if (action == currentAction && controller == currentController)
{
var anchor = new TagBuilder("a");
anchor.Attributes["href"] = "#";
anchor.AddCssClass("currentPageCSS");
anchor.SetInnerText(linkText);
return MvcHtmlString.Create(anchor.ToString());
}
return htmlHelper.ActionLink(linkText, action, controller);
}
}
From Custom ActionLink helper that knows what page you're on
But I am getting
System.Web.Mvc.HtmlHelper' does not contain a definition for
'ActionLink' and no extension method 'ActionLink' accepting a first
argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you
missing a using directive or an assembly reference?
Add this using System.Web.Mvc.Html; on top of your file
Make sure you have the namespace for your extensions class included in your web.config. For example:
namespace MyProject.Extensions
{
public static class LinkExtensions
{
//code
}
}
In your site Web.config and/or Web.config located in your "Views" folder:
<system.web>
<pages>
<namespaces>
<add namespace="MyProject.Extensions" />
</namespaces>
</pages>
</system.web>
Otherwise include a "using" block for the namespace at the top of your view page can work but for common namespaces I would do the above.
ASPX:
<%# Import namespace="MyProject.Extensions" %>
RAZOR:
#using MyProject.Extensions
Don't forget that the first parameter only accepts string. It will show you this error if it's NOT.
Make sure that you have following using in your class file:
using System.Web.Mvc.Html;
This is needed because the HtmlHelper class is located in System.Web.Mvc namespace but the ActionLink extension method is located in System.Web.Mvc.Html namespace.
If your using nopcommerce add this using statement at the top of your view file.
#using Nop.Web.Framework.UI
My issue was, I had incomplete syntax, "#Html.actionLink", in a view. Looks like I had started to add an action link and went a different direction but forgot to remove the partial action link, this caused the same error as above.... So check your syntax as that will throw the same runtime error. Good luck!
I am using MVC3 and I dont want to use Microsoft.Web.Mvc
How do I convert this code to be used in MVC3 ? The view engine is .aspx
Html.Button ("abc", "Button abc", HtmlButtonType.Button)
and also this script
$("button[name=abc]").attr("disabled",true);
Any feedback is appreciated ?
HTML Markup for your button:
<input type="button" name="abc" disabled="true" value="Button abc" />
ASP.NET MVC 3 does not have a built-in HtmlHelper extension method for a button. You could always easily create on:
public static class YourMvcButtonExtensionMethod
{
public static MvcHtmlString Button(this HtmlHelper helper, string text,
IDictionary<string, object> htmlAttributes)
{
// generate the markup for the input/button
}
}
So you really have two options:
use raw HTML markup in your View
create your custom extension method (see above)
"I am using MVC3 and I dont want to use Microsoft.Web.Mvc"
That just sounds confusing...
Anyway you can use the button element instead.
<button disabled='true'>Button abc</button>
I'm working on a MVC3 web application. I want a list of rotation shown in view. But during build I get error:
Error 2971 'System.Web.Mvc.SelectList' does not contain a definition
for 'MakeSelection' and no extension method 'MakeSelection' accepting
a first argument of type 'System.Web.Mvc.SelectList' could be found
(are you missing a using directive or an assembly reference?).
My code in view:
<div class="editor-field">
#Html.DropDownListFor(model => model.JobFiles[i].JobPages[j].UserRotation, (ViewData["rotation"] as SelectList).MakeSelection(Model.JobFiles[i].JobPages[j].UserRotation))
</div>
Please help. Thx in advance.
You error is telling you that the MakeSelection function does not belong to the System.Web.Mvc.SelectList object. I did find this extension method -
public static SelectList MakeSelection(this SelectList list, object selection)
{
return new SelectList(list.Items, list.DataValueField, list.DataTextField, selection);
}
in this question, are you missing the extension method from your code?
Is it possible to use server side include in Razor view engine to include .html or .asp file? We have an .html file and .asp files that contain website menus that are used for all of our websitse. Currently we use server side include for all of our sites so that we only need to change the mensu in one place.
I have the following code in the body of my _Layout.cshtml
<body>
<!--#include virtual="/serverside/menus/MainMenu.asp" -->
<!--#include virtual="/serverside/menus/library_menu.asp" -->
<!--#include virtual="/portfolios/serverside/menus/portfolio_buttons_head.html" -->
#RenderBody()
</body>
Instead of including the content of the file, if I do a view source, I see the literal text.
" <!--#include virtual="/serverside/menus/MainMenu.asp" -->
<!--#include virtual="/serverside/menus/library_menu.asp" -->
<!--#include virtual="/portfolios/serverside/menus/portfolio_buttons_head.html" -->"
#Html.Raw(File.ReadAllText(Server.MapPath("~/content/somefile.css")))
Try making your html page to a cshtml page and including it with:
#RenderPage("_header.cshtml")
Try implementing this HTML helper:
public static IHtmlString ServerSideInclude(this HtmlHelper helper, string serverPath)
{
var filePath = HttpContext.Current.Server.MapPath(serverPath);
// load from file
using (var streamReader = File.OpenText(filePath))
{
var markup = streamReader.ReadToEnd();
return new HtmlString(markup);
}
}
or:
public static IHtmlString ServerSideInclude(this HtmlHelper helper, string serverPath)
{
var filePath = HttpContext.Current.Server.MapPath(serverPath);
var markup = File.ReadAllText(filePath);
return new HtmlString(markup);
}
#RenderPage("PageHeader.cshtml")
<!-- your page body here -->
#RenderPage("PageFooter.cshtml")
This works just fine and can save you a lot of time.
Razor does not support server-side includes. The easiest solution would be copying the menu markup into your _Layout.cshtml page.
If you only needed to include .html files you could probably write a custom function that read the file from disk and wrote the output.
However since you also want to include .asp files (that could contain arbitrary server-side code) the above approach won't work. You would have to have a way to execute the .asp file, capture the generated output, and write it out to the response in your cshtml file.
In this case I would go with the copy+paste approach
Create a HtmlHelper extension method that gets the contents of the files:
public static class HtmlHelpers
{
public static MvcHtmlString WebPage(this HtmlHelper htmlHelper, string url)
{
return MvcHtmlString.Create(new WebClient().DownloadString(url));
}
}
Usage:
#Html.WebPage("/serverside/menus/MainMenu.asp");
Sorry guys for bit old answer but I found some way to attach asp file with razor. Of course you need to do some trick but it works! First of all I created .NET MVC 3 application.
In my _Layout.cshtml I added following line:
#Html.Partial("InsertHelper")
Then I created InsertHelper.aspx in my Shared folder with this content:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!--#include VIRTUAL="/ViewPage1.aspx"-->
ViewPage1.aspx is locaited in my root directory, and has just simple if to check whether it works:
<%
string dummy;
dummy="nz";
%>
<% if (dummy == "nz") { %>
nz indeed
<% } else { %>
not nz
<% } %>
And it works!
Razor is able to render partials with different ViewEngine, and that's why this example is working.
And one more thing: remember to not add following line in both aspx files:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
You can add it only once! Hope it helps!
I had the same issue when I tried to include an .inc file in MVC 4.
To solved this issue, I changed the suffix of the file to .cshtml and I added the following line
#RenderPage("../../Includes/global-banner_v4.cshtml")
Just do:
#Html.Partial("_SliderPartial")
while "_SliderPartial" is your "_SliderPartial.cshtml" file and your fine.
In my _Layout.cshtml I added following line:
#Html.Partial("InsertHelper")
Then I created InsertHelper.aspx in my Shared folder with this content:
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<!--#include VIRTUAL="/ViewPage1.aspx"-->
Why not include a section within your _Layout.cshtml page that will allow you to render sections based on what menu you want to use.
_Layout.cshtml
<!-- Some stuff. -->
#RenderSection("BannerContent")
<!-- Some other stuff -->
Then, in any page that uses that layout, you will have something like this:
#section BannerContent
{
#*Place your ASP.NET and HTML within this section to create/render your menus.*#
}
Html.Include(relativeVirtualPath) Extension Method
I wanted to include files like this for documentation purposes (putting the contents of a file in a <pre> tag).
To do this I added an HtmlHelperExtension with a method that takes a relative virtual path (doesn't have to be an absolute virtual path) and an optional boolean to indicate whether you wish to html encode the contents, which by default my method does since I'm using it primarily for showing code.
The real key to getting this code to work was using the VirtualPathUtility as well as the WebPageBase. Sample:
// Assume we are dealing with Razor as WebPageBase is the base page for razor.
// Making this assumption we can get the virtual path of the view currently
// executing (will return partial view virtual path or primary view virtual
// path just depending on what is executing).
var virtualDirectory = VirtualPathUtility.GetDirectory(
((WebPageBase)htmlHelper.ViewDataContainer).VirtualPath);
Full HtmlHelperExtension Code:
public static class HtmlHelperExtensions
{
private static readonly IEnumerable<string> IncludeFileSupportedExtensions = new String[]
{
".resource",
".cshtml",
".vbhtml",
};
public static IHtmlString IncludeFile(
this HtmlHelper htmlHelper,
string virtualFilePath,
bool htmlEncode = true)
{
var virtualDirectory = VirtualPathUtility.GetDirectory(
((WebPageBase)htmlHelper.ViewDataContainer).VirtualPath);
var fullVirtualPath = VirtualPathUtility.Combine(
virtualDirectory, virtualFilePath);
var filePath = htmlHelper.ViewContext.HttpContext.Server.MapPath(
fullVirtualPath);
if (File.Exists(filePath))
{
return GetHtmlString(File.ReadAllText(filePath), htmlEncode);
}
foreach (var includeFileExtension in IncludeFileSupportedExtensions)
{
var filePathWithExtension = filePath + includeFileExtension;
if (File.Exists(filePathWithExtension))
{
return GetHtmlString(File.ReadAllText(filePathWithExtension), htmlEncode);
}
}
throw new ArgumentException(string.Format(
#"Could not find path for ""{0}"".
Virtual Directory: ""{1}""
Full Virtual Path: ""{2}""
File Path: ""{3}""",
virtualFilePath, virtualDirectory, fullVirtualPath, filePath));
}
private static IHtmlString GetHtmlString(string str, bool htmlEncode)
{
return htmlEncode
? new HtmlString(HttpUtility.HtmlEncode(str))
: new HtmlString(str);
}
}
you can include server side code and aspx file in .cshtml files as below and then inlude classic asp files or html files.
Here are the steps
Index.cshtml
#Html.RenderPartial("InsertASPCodeHelper")
2.InsertASPCodeHelper.aspx
<%# Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>
<!--#include VIRTUAL="~/Views/Shared/Header.aspx"-->
Header.aspx
<!--#include file="/header/header.inc"-->
Using includes is not the correct way to use menus with mvc. You should be using a shared layout and/or partial views.
However if for some odd reason, you must include an html file, here is a way to do it.
Helpers/HtmlHelperExtensions.cs
using System.Web;
using System.Web.Mvc;
using System.Net;
namespace MvcHtmlHelpers
{
public static class HtmlHelperExtensions
{
public static MvcHtmlString WebPage(this HtmlHelper htmlHelper, string serverPath)
{
var filePath = HttpContext.Current.Server.MapPath(serverPath);
return MvcHtmlString.Create(new WebClient().DownloadString(filePath));
}
}
}
Add new namespace to web.config
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="MvcHtmlHelpers"/>
</namespaces>
</pages>
Usage:
#Html.WebPage("/Content/pages/home.html")