Populate a List <> not a Select List [duplicate]

This question already has an answer here:

I’m new to c sharp. I”ve got a MVC Core 2.0 project and I need to populate a list inside a model and return that model to the page. My model looks like this:

public class PageModel
     public string Title {get; set;}
     public List<ChartGroups> Chart { get; set; }    


public class ChartGroups
    public string Freq { get; set; }    
    public string Head { get; set; }

To populate this I’ve got the following:

public PageModel GetChart(){
 PageModel R = new PageModel(); 

 R.Title = "Some Title";
 R.Chart.Add(New ChartGroups {Freq ="Test", Head="Test2"});
 R.Chart.Add(New ChartGroups {Freq ="Test3", Head="Test4"});

The problem is I get an error saying I need to obstinate the object when I get to the R.Chart.Add… line. I’ve been doing this with drop down list and it works just fine….I’m sure I’m missing something simple just can’t see it.

I know that I need to obstinate the object, just not sure how to do so under this context.


ASP.NET SQL datasource combine two queries

I am currently working on a project for my University Degree using ASP.NET webforms with C#. We are tasked with creating a student information system. I am trying to select from the database information about the student and also about who their advisor of studies is. I can get the ID of the advisor of studies, but I then need to select from the user table twice to get the name of the student and the advisor of studies.
I am making use of an SQL datasource to populate boundfields in a gridview.
Below I have 2 SQL statements which I need to somehow combine into 1.

First select to get the name of the advisor of studies (UserId is known from the cookie of the logged in user):

SELECT aos.Forename as StaffForename, aos.Surname as StaffSurname, sdt.AdvisorStudiesID 
FROM [User] aos, [StudentDetails] sdt 
WHERE (sdt.StudentId=@UserId) AND (aos.UserId=sdt.AdvisorStudiesID); 

Second select to get the name and details of the student:

SELECT DISTINCT Forename as StudentForename, Surname as StudentSurname, TitleLong, PersonalTutor, ProfileImage 
FROM [User] u, [StudentDegree] sd, [Degree] d  
WHERE (u.UserId=@UserId) AND (d.DegreeId=sd.DegreeId) AND (sd.StudentId=@UserId);

I had tried just separating these queries with a colon in the SQL datasource, but that did not work(see below)

<asp:SqlDataSource ID="Student" runat="server" ConnectionString="<%$ 
ConnectionStrings:QSIS_Connection %>" SelectCommand="SELECT aos.Forename 
as StaffForename, aos.Surname as StaffSurname, sdt.AdvisorStudiesID FROM 
[User] aos, [StudentDetails] sdt WHERE (sdt.StudentId=@UserId) AND 
(aos.UserId=sdt.AdvisorStudiesID); SELECT DISTINCT Forename as 
StudentForename, Surname as StudentSurname, TitleLong, PersonalTutor, 
ProfileImage FROM [User] u, [StudentDegree] sd, [Degree] d  WHERE 
(u.UserId=@UserId) AND (d.DegreeId=sd.DegreeId) AND 

Any help would be much appreciated.

How to parse JSON without JSON.NET library?

I’m trying to build a Metro application for Windows 8 on Visual Studio 2011.
and while I’m trying to do that, I’m having some issues on how to parse JSON without JSON.NET library (It doesn’t support the metro applications yet).

Anyway, I want to parse this:

   "name":"Prince Charming",
   "genre":"Rock and Metal",

unable to delete directory from SFTP server

I am trying to delete the directory from my SFTP server. I am using EnterpriseDT.Net.Ftp SSHSCPClient for connecting to the server with private key, no password.

When I use the

SSHSCPClient ftpConnection;

//Successfully connected and able to upload the files but


it throws the error

[Message = "This operation is not currently supported."]

How to build multiple c# projects using MSBuild engine without using command prompt?

I am working on windows application project and from that project want to build different multiple c# projects which are in one solution of visual studio 2015 and also want them to be build programmatically individually using MSBuild tool without using command prompt and finally want to show the output in log file not in command prompt (means those project is building successfully or having any errors like this message in log file)

Do I need to use any MSBuild API and how to add in this project?

I have seen many questions like this (not exactly same) but it didn’t work for me. please can anybody help me with this?

correct record value is not insert into second table

I am inserting some data from one file to another,first file has three
different value records,when loop finish, when I see second file it has three records but with repeated with same value, can you help me out what is wrong with my code.

Loop from Old file to new file

foreach (DataRow drtableOld in orderTable.Rows)
    command.CommandType = CommandType.Text;
    command.CommandText = "insert into Data ([Terminal],[Token_no],[Date],[Time],[Mode]) values(?,?,?,?,?)";
    command.Parameters.AddWithValue("@cTerminal", drtableOld["Terminal"]);
    command.Parameters.AddWithValue("@cToken", drtableOld["Token"].ToString().PadLeft(6,'0')  );
    command.Parameters.AddWithValue("@cDate", drtableOld["Date"]);
    command.Parameters.AddWithValue("@cTime", drtableOld["Time"]);
    command.Parameters.AddWithValue("@cMode", "T");
    command.Connection = yourConnectionHandler;

How to pass a value from JavaScript to code behind?

I want get a value from js to code behind but the value is always an empty string.

I tried to pass the value from js to a label with runat="server" specified but in vain.


<input type="hidden" runat="server" id="Val1"/>


document.getElementById("Val1").value = MyFunction();

function MyFunction() 
    var value = "111";

code behind:

protected void sss(object sender, EventArgs e)
    string aa = Val1.Value;

Render View to String caching issue

For my project I currently implemented a ViewRender for my asp.net core application. It generates Views without a controller to html, this works fine using the following code:

public class ViewRenderService : IViewRenderService
    private readonly IRazorViewEngine _razorViewEngine;
    private readonly ITempDataProvider _tempDataProvider;
    private readonly IServiceProvider _serviceProvider;

    public ViewRenderService(IRazorViewEngine razorViewEngine,
        ITempDataProvider tempDataProvider,
        IServiceProvider serviceProvider)
        _razorViewEngine = razorViewEngine;
        _tempDataProvider = tempDataProvider;
        _serviceProvider = serviceProvider;

    public async Task<string> RenderToStringAsync(string viewName, object model)
        var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider };

        var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());
        string viewgerendered = "";
            using (var sw = new StringWriter())
                var viewResult = _razorViewEngine.GetView(viewName, viewName, false);

                if (viewResult.View == null)
                    throw new ArgumentNullException($"{viewName} does not match any available view");

                var viewDictionary = new ViewDataDictionary(new EmptyModelMetadataProvider(), new ModelStateDictionary())
                    Model = model

                var viewContext = new ViewContext(
                    new TempDataDictionary(actionContext.HttpContext, _tempDataProvider),
                    new HtmlHelperOptions()

                await viewResult.View.RenderAsync(viewContext);

                viewgerendered = sw.ToString();
                return viewgerendered;
        catch (Exception e)
            object temp = e.Message + " - " + e.StackTrace;
            return temp.ToString();

    public Task RenderToStringAsync(string v)
        throw new NotImplementedException();

Source: https://ppolyzos.com/2016/09/09/asp-net-core-render-view-to-string/

Changes which are made to views which use this renderer are not updated without restarting the application itself. Diving further into it, the views are cached. A comment within the source mentions using the _razorViewEngine.GetView method should get rid of my caching issue. However this doesn’t work.

What I got, trying to figure out a way to register a new ViewRender, with a slight modification of the ViewRenderService.

//Seems not to be available on asp.net core 2.0...
services.AddMvc().Configure<MvcViewOptions>(options =>

And to overload the RazorViewEngine to expose the ViewLookupCache, where supposedly the view cache is located.

  public class CustomViewEngine : RazorViewEngine
        public CustomViewEngine(
            IRazorPageFactoryProvider pageFactory, 
            IRazorPageActivator pageActivator,
            HtmlEncoder htmlEncoder, 
            IOptions<RazorViewEngineOptions> optionsAccessor, 
            Microsoft.AspNetCore.Razor.Language.RazorProject razorProject, 
            ILoggerFactory loggerFactory, 
            System.Diagnostics.DiagnosticSource diagnosticSource) : 
            base(pageFactory, pageActivator, htmlEncoder, optionsAccessor,razorProject,loggerFactory, diagnosticSource){ }

        public void RemoveCachedView(string view)

There’s not a lot to find on how caching is done within asp.net core 2.0 for views and clearing a particular view / set of. Basically I want to find a way how I can flush an entire selection of cached views as a command, for performance reasons.

Namespace from other projects not available

I have a solution with 4 projects with these namespaces:

project name TPCO

namespace TPCO
namespace TPCO.Controllers
namespace TPCO.Models

project name TPCO.Core

namespace TPCO.Core.Data
namespace TPCO.Core.Domain
namespace TPCO.Core.Models

project name TPCO.Data

namespace TPCO.Data

project name TPCO.Tests

namespace TPCO.Tests.Controllers

The TPCO.Core and TPCO.Data projects were originally part of an ASP.Net Web Application. I imported them into an ASP.Net MVC5 application solution containing the TPCO and TPCO.Test projects.

For some reason, I cannot see any of the namespaces from TPCO.Core or TPCO.Data from TPCO. I also cannot see TPCO, TPCO.Controllers or TPCO.Models from TPCO.Core or TPCO.Data projects. However, I can see TPCO.Core.* from TPCO.Data and vice versa.

And from TPCO.Tests, I can only see the namespaces from the TPCO and TPCO.Tests projects.

All projects have same target framework, per: Namespace not available in other project
Also, ALL classes in TPCO.Core and TPCO.Data are marked public

What is going on and how do I remedy this? Could it be that the TPCO.Core and TPCO.Data projects reside outside the folder structure of the MVC app that is causing this?

Is this constructor violating the Single Responsibility Principle?

I’m trying to force myself to use SOLID principles and write unit testable code. Lately, I have been getting paranoid and indecisive when writing code because I get the feeling that I’m always violating some principle.

Consider the below class. JavascriptPropertyInitializer is responsible for detecting a list of properties that have a special attribute in a given class, and rendering some javaScript code. Does it have too many responsibilities? Is the constructor doing too much?

I know I’m instantiating a dictionary in the constructor and I’m aware that instantiating concrete objects is a known violation. Yeah, I know, I’m supposed to inject it via the constructor, but why? What’s the harm of my class depending on a concrete dictionary?

public class JavascriptPropertyInitializer
    private readonly HtmlTextWriter _writer;
    private readonly object _containerObject;
    private readonly string _javascriptObjectName;
    private readonly Dictionary<string, string> _settings;
    private List<PropertyInfo> _customWebControls;

    public JavascriptPropertyInitializer(HtmlTextWriter writer, object containerObject, string javascriptObjectName)
        _writer = writer;
        _containerObject = containerObject;
        _javascriptObjectName = javascriptObjectName;
        _settings = new Dictionary<string, string>();
        ValidateParameters(writer, containerObject, javascriptObjectName);

    pubic void Render()