I get this error
Cannot implicitly convert System.Collections.Generic.List to System.Collections.Generic.IEnumerable
when trying to use a list to build out #Html.DropDownList() in a page built using C# Razor.
There is a C# class called SubProgram.cs with the following method that returns a List<>:
public List<SubProgram> SubProgramCodeDescriptionList()
{
List<SubProgram> SubPrograms = new List<SubProgram>();
// Get the list of SubPrograms for this AcctIII role_code from BudgetAcct3ToSubProgram table
using (var db = Database.Open("DBNAME"))
{
string sql = #"
SELECT l.SubProgramID, l.SubProgram + ' ' + l.SubProgramDesc AS SubProgramDesc
FROM BARF_SubPrograms l
WHERE l.Deleted = 0
ORDER BY l.SubProgramDesc";
var ListSubPrograms = db.Query(sql);
foreach (var SubProgram in ListSubPrograms)
{
SubProgram item = new SubProgram ();
item.SubProgramID = SubProgram.SubProgramID;
item.SubProgramCodeDescr = SubProgram.SubProgramDesc;
SubPrograms.Add(item);
}
db.Close();
return SubPrograms;
}
}
Here is the SubProgram class this method is a part of:
public class SubProgram
{
private int subprogramid;
private string subprogramcode;
private string subprogramcodedescr;
public int SubProgramID
{
get { return subprogramid; }
set { subprogramid = value; }
}
public string SubProgramCode
{
get { return subprogramcode; }
set { subprogramcode = value; }
}
public string SubProgramCodeDescr
{
get { return subprogramcodedescr; }
set { subprogramcodedescr = value; }
}
}
In the C# section of a Razor page, I create an object of type SubProgram to fill the SubProgramList:
// Create List boxes variable need for this add
List<SubProgram> SubProgramIDdropdownlist = new List<SubProgram>();
// Create SubProgram object so the method can be called
SubProgram subProgram = new SubProgram();
// Pass object to method SubProgramIDdropdownlist to return all of the SubPrograms
SubProgramIDdropdownlist = subProgram.SubProgramCodeDescriptionList();
In the body section of the HTML page below this C# Razor section above, I try to populate the DropDownList with the above code:
<label class="FieldLabels">"Search SubPrograms"</label>
#Html.DropDownList("SubProgramCodes",
SubProgramIDdropdownlist,
new {
#id = "Column1",
#class = "EditTextBox",
}
)
In this last section, the error occurs on SubProgramIDdropdownlist and this is where I get the error
Cannot implicitly convert System.Collections.Generic.List to System.Collections.Generic.IEnumerable
There are other related posts, but not coming from a class method. Please help, I know this needs to probably use a cast, but not even sure where to begin to get this to cast correctly.
Two ways I can think of:
On Razor Page using AsEnumerable
#Html.DropDownList("SubProgramCodes",SubProgramIDdropdownlist.AsEnumarable(),new { #id = "Column1", #class = "EditTextBox"})
OR
Change the return type from List<SubProgram> to IEnumerable<SubProgram>
public IEnumerable<SubProgram> SubProgramCodeDescriptionList(){...}
Thank you tontonsevilla, your answer was helpful in solving this.
The final solution I came up with is that there was a conflict between two namespaces that both contained SelectListItem in both of them: System.Web.Mvc and System.Web.WebPages.Html.
Since I am primarily using Razor pages and not MVC for this project, I removed the #using System.Web.Mvc at the top of the Razor C# page because the error made it clear that SelectListItem is found in both System.Web.Mvc and in System.Web.WebPages.Html and I clearly needed to use one or the other, but not both. I was able to cast these to get them to work, but this was just a lot of extra code that was not needed when I realized it was a name conflict.
Using both namespaces created a conflict between these two namespaces because SelectListItem appears to be in both namespaces.
I'm trying to create a ResetPassword Page and I need to create something like that!
myApi.azure.com/ResetPassword?hash=YYYYYYYYYYYYYY
I already know how to create a link to another controller, but that way it would trigger the Action just with the click, and what I need is pass the hash as parameter inside of that URL and them, call a controller!
var link = new Uri(Url.Link("ValidationEmailUser", new { Code = emailToken }));
Something like this:
public IHttpActionResult RedirectAction()
{
var urlFormat = string.Format("https://www3.olx.com.br/account/forgotten_password/?hash={0}", emailToken);
var location = new Uri(urlFormat);
return this.Redirect(location);
}
I'm a newbie. I pass a parameter from a UIViewController to another with this method:
FirstViewController:
string parameter = "test";
var navigation = ServiceLocator.Current.GetInstance<INavigationService>();
navigation.NavigateTo("SecondViewController", parameter);
And after I would like to get my parameter:
SecondViewController:
var nav = new NavigationService().Initialize(NavigationController);
UIViewController controller = nav.NavigationController.TopViewController ; //The UIKit.UIViewController that was navigated to
string param = (String)nav.GetAndRemoveParameter(controller);
But the parameter result is null. Where I make mistakes? How can I get my parameter?
I solved this error in this way:
var navigation = (NavigationService)ServiceLocator.Current.GetInstance<INavigationService>();
I must to use a cast before this line of code.
Thank you all
I want to call the #Html.ActionLink method inside a c# function to return a string with a link on it.
Something like this:
string a = "Email is locked, click " + #Html.ActionLink("here to unlock.", "unlock") ;
Assuming that you want to accomplish this in your controller, there are several hoops to jump through. You must instantiate a ViewDataDictionary and a TempDataDictionary. Then you need to take the ControllerContext and create an IView. Finally, you are ready to create your HtmlHelper using all of these elements (plus your RouteCollection).
Once you have done all of this, you can use LinkExtensions.ActionLink to create your custom link. In your view, you will need to use #Html.Raw() to display your links, to prevent them from being HTML encoded. Here is the necessary code:
var vdd = new ViewDataDictionary();
var tdd = new TempDataDictionary();
var controllerContext = this.ControllerContext;
var view = new RazorView(controllerContext, "/", "/", false, null);
var html = new HtmlHelper(new ViewContext(controllerContext, view, vdd, tdd, new StringWriter()),
new ViewDataContainer(vdd), RouteTable.Routes);
var a = "Email is locked, click " + LinkExtensions.ActionLink(html, "here to unlock.", "unlock", "controller").ToString();
Having shown all of this, I will caution you that it is a much better idea to do this in your view. Add the error and other information to your ViewModel, then code your view to create the link. If this is needed across multiple views, create an HtmlHelper to do the link creation.
UPDATE
To address one.beat.consumer, my initial answer was an example of what is possible. If the developer needs to reuse this technique, the complexity can be hidden in a static helper, like so:
public static class ControllerHtml
{
// this class from internal TemplateHelpers class in System.Web.Mvc namespace
private class ViewDataContainer : IViewDataContainer
{
public ViewDataContainer(ViewDataDictionary viewData)
{
ViewData = viewData;
}
public ViewDataDictionary ViewData { get; set; }
}
private static HtmlHelper htmlHelper;
public static HtmlHelper Html(Controller controller)
{
if (htmlHelper == null)
{
var vdd = new ViewDataDictionary();
var tdd = new TempDataDictionary();
var controllerContext = controller.ControllerContext;
var view = new RazorView(controllerContext, "/", "/", false, null);
htmlHelper = new HtmlHelper(new ViewContext(controllerContext, view, vdd, tdd, new StringWriter()),
new ViewDataContainer(vdd), RouteTable.Routes);
}
return htmlHelper;
}
public static HtmlHelper Html(Controller controller, object model)
{
if (htmlHelper == null || htmlHelper.ViewData.Model == null || !htmlHelper.ViewData.Model.Equals(model))
{
var vdd = new ViewDataDictionary();
vdd.Model = model;
var tdd = new TempDataDictionary();
var controllerContext = controller.ControllerContext;
var view = new RazorView(controllerContext, "/", "/", false, null);
htmlHelper = new HtmlHelper(new ViewContext(controllerContext, view, vdd, tdd, new StringWriter()),
new ViewDataContainer(vdd), RouteTable.Routes);
}
return htmlHelper;
}
}
Then, in a controller, it is used like so:
var a = "Email is locked, click " +
ControllerHtml.Html(this).ActionLink("here to unlock.", "unlock", "controller").ToString();
or like so:
var model = new MyModel();
var text = ControllerHtml.Html(this, model).EditorForModel();
While it is easier to use Url.Action, this now extends into a powerful tool to generate any mark-up within a controller using all of the HtmlHelpers (with full Intellisense).
Possibilities of use include generating mark-up using models and Editor templates for emails, pdf generation, on-line document delivery, etc.
You could create an HtmlHelper extension method:
public static string GetUnlockText(this HtmlHelper helper)
{
string a = "Email is locked, click " + helper.ActionLink("here to unlock.", "unlock");
return a;
}
or if you mean to generate this link outside of the scope of an aspx page you'll need to create a reference to an HtmlHelper and then generate. I do this in a UrlUtility static class (I know, people hate static classes and the word Utility, but try to focus). Overload as necessary:
public static string ActionLink(string linkText, string actionName, string controllerName)
{
var httpContext = new HttpContextWrapper(System.Web.HttpContext.Current);
var requestContext = new RequestContext(httpContext, new RouteData());
var urlHelper = new UrlHelper(requestContext);
return urlHelper.ActionLink(linkText, actionName, controllerName, null);
}
Then you can write the following from wherever your heart desires:
string a = "Email is locked, click " + UrlUtility.ActionLink("here to unlock.", "unlock", "controller");
There's a couple things bad about these other answers...
Shark's answer requires you to bring the LinkExtensions namespace into C#, which is not wrong, but undesirable to me.
Hunter's idea of making a helper is a better one, but still writing a helper function for a single URL is cumbersome. You could write a helper to help you build strings that accepted parameters, or you could simply do it the old fashion way:
var link = "Email is... click, to unlock.";
#counsellorben,
i see no reason for the complexity; the user wants only to render an Action's routing into a hard string containing an anchor tag. Moreover, ActionLink() in a hard-written concatenated string buys one nothing, and forces the developer to use LinkExtensions whidh are intended for Views.
If the user is diehard about using ActionLink() or does not need (for some reason) to calculate this string in the constructor, doing so in a view is much better.
I still stand by and recommend the answers tvanfosson and I provided.
Your best bet is to construct the link manually using the UrlHelper available in the controller. Having said that, I'm suspicious that there is probably a better way to handle this in a view or partial view, shared or otherwise.
string a = "Email is locked, click <a href=\""
+ Url.Action( "unlock" )
+ "\">here to unlock.</a>";
Maybe try this:
string a = "Email is locked, click " + System.Web.Mvc.Html.LinkExtensions.ActionLink("here to unlock.", "unlock");
I am using LINQ to SQL in an ASP.NET project. While inserting the table I need to convert the values to the particular table object and I need to insert.
For that I created a new constructor in that table with parameter so that I can assign my value to that table object , the assign the functionality is working but while inserting (obj.TS_Questions.InsertOnSubmit(mytableobject);) I get null exception.
my code::
default constructor for my table
public TS_Question()
{
this._TS_Options = new EntitySet<TS_Option>(new Action<TS_Option>(this.attach_TS_Options), new Action<TS_Option>(this.detach_TS_Options));
this._TS_QuestGroups = new EntitySet<TS_QuestGroup>(new Action<TS_QuestGroup>(this.attach_TS_QuestGroups), new Action<TS_QuestGroup>(this.detach_TS_QuestGroups));
this._TS_QuestRecords = new EntitySet<TS_QuestRecord>(new Action<TS_QuestRecord>(this.attach_TS_QuestRecords), new Action<TS_QuestRecord>(this.detach_TS_QuestRecords));
this._TS_Admin = default(EntityRef<TS_Admin>);
this._TS_LevelType = default(EntityRef<TS_LevelType>);
this._TS_OptionTypeLT = default(EntityRef<TS_OptionTypeLT>);
OnCreated();
}
constructor created by me
public TS_Question(Guid Quest_QuestIDBL, string Quest_NameBL, Nullable<Guid> Quest_OptionTypeIDBL, Guid Quest_AdminIDBL, Guid Ques_LevelIDBL, int Quest_TimeBL, int Quest_MarkBL, string Qest_ExplanationBL, Nullable<bool> Qest_IsMultipleAnswerBL)
{
this._TS_Options = new EntitySet<TS_Option>(new Action<TS_Option>(this.attach_TS_Options), new Action<TS_Option>(this.detach_TS_Options));
this._TS_QuestGroups = new EntitySet<TS_QuestGroup>(new Action<TS_QuestGroup>(this.attach_TS_QuestGroups), new Action<TS_QuestGroup>(this.detach_TS_QuestGroups));
this._TS_QuestRecords = new EntitySet<TS_QuestRecord>(new Action<TS_QuestRecord>(this.attach_TS_QuestRecords), new Action<TS_QuestRecord>(this.detach_TS_QuestRecords));
this._TS_Admin = default(EntityRef<TS_Admin>);
this._TS_LevelType = default(EntityRef<TS_LevelType>);
this._TS_OptionTypeLT = default(EntityRef<TS_OptionTypeLT>);
OnCreated();
this._Quest_QuestID = Quest_QuestIDBL;
this._Quest_Name = Quest_NameBL;
if (Quest_OptionTypeIDBL != null)
{
this._Quest_OptionTypeID = Quest_OptionTypeIDBL;
}
this._Quest_AdminID = Quest_AdminIDBL;
this._Ques_LevelID = Ques_LevelIDBL;
this._Quest_Time = Quest_TimeBL;
this._Quest_Mark = Quest_MarkBL;
this._Qest_Explanation = Qest_ExplanationBL;
this._Qest_IsMultipleAnswer = Qest_IsMultipleAnswerBL;
}
Please help me out from this problem
Honestly, I haven't looked too deep, but it looks like that OnCreated is sitting a little far north... You probably want to call it after you're done setting up your variables. Other than that i'd say make sure you're properly initializing everything in the method calling the constructor.
You can call default constructor like this, it works fine for me:
public partial class MyClass
{
public MyClass(string fieldValue1,int fieldValue2)
: this()
{
this.field1= fieldValue1;
this.field2 = fieldValue2;
}
}
If this do the trick, you can read more about using contructors in C# here.