I'm using structuremap with hangfire on asp.net core, no error on application but hangfire not process queue/schedule task even though data already on database. Here my snippet configuration

public IServiceProvider ConfigureServices(IServiceCollection services)
        // setup automapper
        var config = new AutoMapper.MapperConfiguration(cfg =>
            cfg.AddProfile(new AutoMapperProfileConfiguration());

        var mapper = config.CreateMapper();

        // Bind settings parameter

        // Add framework services.
        services.Configure<RouteOptions>(options => options.LowercaseUrls = true);
        services.AddDbContext<DefaultContext>(options =>

        services.AddHangfire(options => 

        // ASP.NET use the StructureMap container to resolve its services.
        return ConfigureIoC(services);

    public IServiceProvider ConfigureIoC(IServiceCollection services)
        var container = new Container();


        container.Configure(config =>
            // Register stuff in container, using the StructureMap APIs...
            config.Scan(_ =>
            config.For<ILog>().Use(c => LoggerFactory.LoggerFor(c.ParentType)).AlwaysUnique();
            XmlDocument log4netConfig = new XmlDocument();

            var repo = LogManager.CreateRepository(
                Assembly.GetEntryAssembly(), typeof(log4net.Repository.Hierarchy.Hierarchy));

            XmlConfigurator.Configure(repo, log4netConfig["log4net"]);
            //Populate the container using the service collection

        return container.GetInstance<IServiceProvider>();

Is there any better way using hangfire and structuremap on asp.net core? Am I missing something so hangfire not working properly?

i am getting error pls help i am new to asp.net

Public Shared Function GetPOListForWO(ByVal p_UserContactID As Integer, ByVal p_WONumber As Integer) As dsPOList
            Dim ds As New dsPOList
            Using ta As New dsPOListTableAdapters.wsm_View_PurchaseOrderListTableAdapter
                    ta.FillByWONumber(ds.wsm_View_PurchaseOrderList, p_UserContactID, p_WONumber)
                Catch ex As Exception
                End Try
            End Using
            Return ds
        End Function

I have more than 100 excel files.My job is to merge to all the excel files into one excel. I did easily by writing the C# program for merging excels. Now I need to Identify the records as per the excel file name.I mean I need to add the actual Excel file name to the new columns for all rows exists.

For Example: I have excel Dom.xls having 2 rows in that excel.

   Name   SSN   Address
    1      0923  1 winter st
    2      0924  2 winter st

Now I need the excel should create new column named"Excel File Name"

and should write the file name like beow

   Name   SSN   Address         Excel File Name
    1      0923  1 winter st     dom.xls
    2      0924  2 winter st     dom.xls

How Do I achieve this.

Either I need this requirement before merging all the excels or after merging the excels.

Below code I used to merge all excels.

class Program
    static void Main(string[] args)
        MergeExcel.DoMerge(new string[]
          @"C:\Users\dom\Desktop\Reim Account\032 - dom_AMESBURY.xlsx",
          @"C:\Users\dom\Desktop\Reim Account\128 - dom_BRAINTREE.xlsx",
          @"C:\Users\dom\Desktop\Reim Account\960 - dom_RETIREMENT.xlsx"....etc
          @"D:\MyExcel\dom.xlsx", "V", 2);

public class MergeExcel
    Excel.Application app = new Microsoft.Office.Interop.Excel.ApplicationClass();

    //initialize the object of saved target 
    Excel.Workbook bookDest = null;
    Excel.Worksheet sheetDest = null;

    //initialize the object of read data
    Excel.Workbook bookSource = null;
    Excel.Worksheet sheetSource = null;
    string[] _sourceFiles = null;
    string _destFile = string.Empty;
    string _columnEnd = string.Empty;
    int _headerRowCount = 0;
    int _currentRowCount = 0;
    public MergeExcel(string[] sourceFiles, string destFile, string columnEnd, int headerRowCount)

        //Use class Missing case to indicate the missing value. e.g. when you call the method that has default parameter value
        bookDest = (Excel.WorkbookClass)app.Workbooks.Add(Missing.Value);
        sheetDest = bookDest.Worksheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value) as Excel.Worksheet;
        sheetDest.Name = "Data";
        _sourceFiles = sourceFiles;
        _destFile = destFile;
        _columnEnd = columnEnd;
        _headerRowCount = headerRowCount;

    //open worksheet
    void OpenBook(string fileName)
        bookSource = app.Workbooks._Open(fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
        sheetSource = bookSource.Worksheets[1] as Excel.Worksheet;

    //close worksheet
    void CloseBook()
        bookSource.Close(false, Missing.Value, Missing.Value);

    //copy table header
    void CopyHeader()
        Excel.Range range = sheetSource.get_Range("A1", _columnEnd + _headerRowCount.ToString());
        range.Copy(sheetDest.get_Range("A1", Missing.Value));
        _currentRowCount += _headerRowCount;

    //copy data
    void CopyData()
        int sheetRowCount = sheetSource.UsedRange.Rows.Count;
        Excel.Range range = sheetSource.get_Range(string.Format("A{0}", _headerRowCount), _columnEnd + sheetRowCount.ToString());
        range.Copy(sheetDest.get_Range(string.Format("A{0}", _currentRowCount), Missing.Value));
        _currentRowCount += range.Rows.Count;

    //save the result
    void Save()
        bookDest.Saved = true;

    //exit the process
    void Quit()
    void DoMerge()

        //declare variate bool to judge if copy table header
        bool b = false;
        foreach (string strFile in _sourceFiles)
            if (b == false)
                b = true;
    /// merge table
    /// source file
    /// object file
    /// the sign of the last column
    /// the number of rows of table header
    public static void DoMerge(string[] sourceFiles, string destFile, string columnEnd, int headerRowCount)
        new MergeExcel(sourceFiles, destFile, columnEnd, headerRowCount).DoMerge();

I'm trying to find a way to scaffold a new ASP.NET Core site that runs on the full .NET Framework (net461) and contains a unit test project. Is this doable? All of the options for dotnet new mvc don't seem to allow net461 as a framework. The same is true for the xunit project type.

This question already has an answer here:

Hi I am new to MVC I am trying to disable a button if a few textboxfor fields are not entered or are null. I have tried the following code below but no luck, I get an object null error.

@if (String.IsNullOrEmpty(modelData.Email))
    <input type="submit" class="btn btn-default" value="Register" onclick="JavascriptFunction()" disabled="disabled" />
    <input type="submit" class="btn btn-default" value="Register" onclick="JavascriptFunction()" />

HTML Text box definition

@Html.TextBoxFor(m => m.Email, new { @placeholder = "example: dlamini@gmail.com", @class = "form-control", id = "message", onkeypress = "capLock(event)" })

This happens when the Registration.cshtml page loads, please assist.

I am Developing RDLC report with export to excel functionality on button click in Asp.net. below code where i am using while button click i am not getting http response please help me how it will get http response ,Thanks

    public void btnExportAll_Click(Object sender, EventArgs e)
        string Name = ddl.SelectedValue;
        string Type = Productddl.SelectedValue;
        string Id =  ddl.SelectedValue;
        DateTime BD = Convert.ToDateTime(txtDate.Text);
        DataSet ds = new DataSet();
        ds = GetCashDataSource(BD, Name, Convert.ToInt32(Id), Flag);
        ReportViewer viewer = new ReportViewer();
        Warning[] warnings;
        string[] streamids;
        string mimeType;
        string encoding;
        string extension;
        string filename;
        viewer.LocalReport.ReportPath = 
        ReportDataSource("Balance", ds.Tables[0]));
        ReportDataSource("Name", ds.Tables[1]));
        ReportDataSource("Amount", ds.Tables[2]));
        viewer.LocalReport.DataSources.Add(new ReportDataSource("Amount", 
        viewer.LocalReport.DataSources.Add(new ReportDataSource("GrandTotal", ds.Tables[4]));
        viewer.LocalReport.DataSources.Add(new ReportDataSource("Diff", ds.Tables[5]));
        viewer.LocalReport.DataSources.Add(new ReportDataSource("Name", ds.Tables[6]));
        viewer.LocalReport.EnableHyperlinks = true;
        string Code = "10,12";
        ReportParameter rp1 = new ReportParameter("BusinessDate", txtDate.Text, false);
        ReportParameter rp2 = new ReportParameter("DropDown", ddl.SelectedValue, false);
        ReportParameter rp3 = new ReportParameter("Id", Code, false);
        viewer.LocalReport.SetParameters(new ReportParameter[] { rp1, rp2, rp3 })
        byte[] bytes = viewer.LocalReport.Render(
           "Excel", null, out mimeType, out encoding,
            out extension,
           out streamids, out warnings);
        filename = string.Format("{0}.{1}", "ExportToExcel", "xls");
        Response.Buffer = true;
        Response.ContentType = mimeType;
        Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);
        catch (Exception ex)
            Page.ClientScript.RegisterStartupScript(this.GetType(), "ErrorAlert", "alert('Error while generating PDF.');", true);


My DB table is described via class MyClass:

public class MyClass
 public int ID {get; set;}
 public int AnotherID {get; set;}
 public string Variation {get; set;}

Prior to BinarySearch I can sort this list via SQL Order By [Variation] and get it sorted by SQL Server or sort using Web Server via List<T>.Sort(). Do these lists will be absolutely equal under any circumstances?

P.S. The column/property of interest is Variation. SQL Server: T-SQL, Web Server: IIS.

I have worked in Web Application exporting datas in grid and I want to Save them Using Save as dialog box either in C#,Javascript.

function openDialog() {

        var input = $(document.createElement('input'));
        input.attr("type", "file")
        return false;


I have this data in my database

ID  Name    Description  Option
1   AAA       a1         1,2,3,4,5
2   BBB       b2         1,2,3,4,5
3   CCC       c3         1,2,3,4,5
4   DDD       d4

I want to create Option as dropdown list option and split it by "," 1st dropdown contain Name 2nd dropdown contain Option, I need 2nd option get removed when 1st dropdown changed as you seen the last option has no option, so I need it to be blank.

Previously I make it like this:

@if (ListOperator != null){
string[] OP = ListOperator[0].Option.Split(',');
for (int j = 0; j < OP.Length; j++){
   <option value="@OP[j]">@OP[j]</option>

But it look like does not loop for the data count. Any idea?

Im new in Asp.net MVC and have been learning Entity Framework using the code first approach. I am working with visual studio 2017 Community but cannot find a default connection​string in the web.config file... I don't know how to pass this.

I'm trying to get an id in the click of my button. My button is inside a GridView

<asp:GridView runat="server" AutoGenerateColumns="false"
                            ID="UsersGridView" AllowPaging="true"
                            CssClass="table table-hover table-striped"
                            UseAccessibleHeader="true" GridLines="None">
                        <asp:BoundField DataField="User.FullName" HeaderText="User" />
                        <asp:BoundField DataField="Book.Title" HeaderText="Book" />
                        <asp:BoundField DataField="BooksReserved.DateOut" HeaderText="Return Date" 
                            FooterStyle-BackColor="#ff0000" DataFormatString="{0:d}" />
                        <asp:TemplateField ShowHeader="false">
                                <asp:LinkButton ID="userProfile" runat="server" OnCommand="userProfile_Command"
                                    CommandArgument='<% Eval("User.Id") %>'
                                    Text="Open User Profile" CssClass="btn btn-success" />

In the code behind method Page_Load, I load the data for my gridview from 3 tables:

protected void Page_Load(object sender, EventArgs e)
    // Users Grid
    var query = from u in db.Users
                join br in db.BooksReserveds on u.Id equals br.UserId
                join b in db.Books on br.BookId equals b.Id
                where br.DateOut < DateTime.Today
                orderby br.DateOut
                select new { User = u, BooksReserved = br, Book = b };

    UsersGridView.DataSource = query.ToList();
    UsersGridView.DataBind(); }

And in the click of the button, I try to get the id:

protected void userProfile_Command(object sender, CommandEventArgs e)
        int id = Int32.Parse(e.CommandArgument.ToString());
        var query = from u in db.Users
                    where u.Id == id
                    select u;
    } catch(Exception any)

I'm getting the exception: "Input string was not in a correct format."

Does anyone know why?


I have been working on a website for an employer which contains database information, allowing for the user to edit the information at will. A request that I have received is to add a button called Deactivate which onclick should add the tag 'X' to a column named 'Inactive' stating that the row is in fact inactive to any rows with a checkbox ticked. The checkboxes have already been added to the GridView.

I have tried adding stored procedures through SQL Server Management Studio however following the tutorials listed in the Microsoft Documents, I do not have the option to add / create new stored procedure when I right click the stored procedures folder.

I have been searching the internet for days and I don't know whether I am not finding the correct answers or whether I simply do not understand them properly.

SQL Deactivate Command Pseudocode

UPDATE Products SET Inactive="X" WHERE chkBox="True"


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Customer_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <form id="form1" runat="server">

        <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="ProductID" DataSourceID="SqlDataSource1" OnSelectedIndexChanged="GridView1_SelectedIndexChanged" BackColor="White" BorderColor="White" BorderStyle="Ridge" BorderWidth="2px" CellPadding="3" CellSpacing="1" GridLines="None">
                <asp:CommandField ShowEditButton="True" />
                <asp:CheckBox ID="chkRow" runat="server" />
                <asp:BoundField DataField="ProductID" HeaderText="ProductID" ReadOnly="True" SortExpression="ProductID" InsertVisible="False" />
                <asp:BoundField DataField="ProductName" HeaderText="ProductName" SortExpression="ProductName" />
                <asp:BoundField DataField="SupplierID" HeaderText="SupplierID" SortExpression="SupplierID" />
                <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" SortExpression="CategoryID" />
                <asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit" SortExpression="QuantityPerUnit" />
                <asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice" SortExpression="UnitPrice" />
                <asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock" SortExpression="UnitsInStock" />
                <asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder" SortExpression="UnitsOnOrder" />
                <asp:BoundField DataField="ReorderLevel" HeaderText="ReorderLevel" SortExpression="ReorderLevel" />
                <asp:CheckBoxField DataField="Discontinued" HeaderText="Discontinued" SortExpression="Discontinued" />
                <asp:BoundField DataField="Inactive" HeaderText="Inactive" SortExpression="Inactive" />
            <FooterStyle BackColor="#C6C3C6" ForeColor="Black" />
            <HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#E7E7FF" />
            <PagerStyle BackColor="#C6C3C6" ForeColor="Black" HorizontalAlign="Right" />
            <RowStyle BackColor="#DEDFDE" ForeColor="Black" />
            <SelectedRowStyle BackColor="#9471DE" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F1F1F1" />
            <SortedAscendingHeaderStyle BackColor="#594B9C" />
            <SortedDescendingCellStyle BackColor="#CAC9C9" />
            <SortedDescendingHeaderStyle BackColor="#33276A" />
        <asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:NorthWindConnectionString %>"
        "DELETE FROM [Products] WHERE [ProductID] = @ProductID"
        "INSERT INTO [Products] ([ProductName], [SupplierID], [CategoryID], [QuantityPerUnit], [UnitPrice], [UnitsInStock], [UnitsOnOrder], [ReorderLevel], [Discontinued], [Inactive]) VALUES (@ProductName, @SupplierID, @CategoryID, @QuantityPerUnit, @UnitPrice, @UnitsInStock, @UnitsOnOrder, @ReorderLevel, @Discontinued, @Inactive)"
        "SELECT * FROM [Products]"
        "UPDATE [Products] SET [ProductName] = @ProductName, [SupplierID] = @SupplierID, [CategoryID] = @CategoryID, [QuantityPerUnit] = @QuantityPerUnit, [UnitPrice] = @UnitPrice, [UnitsInStock] = @UnitsInStock, [UnitsOnOrder] = @UnitsOnOrder, [ReorderLevel] = @ReorderLevel, [Discontinued] = @Discontinued, [Inactive] = @Inactive WHERE [ProductID] = @ProductID">
        <asp:Parameter Name="ProductID" Type="Int32" />
        <asp:Parameter Name="ProductName" Type="String" />
        <asp:Parameter Name="SupplierID" Type="Int32" />
        <asp:Parameter Name="CategoryID" Type="Int32" />
        <asp:Parameter Name="QuantityPerUnit" Type="String" />
            <asp:Parameter Name="UnitPrice" Type="Decimal" />
            <asp:Parameter Name="UnitsInStock" Type="Int16" />
            <asp:Parameter Name="UnitsOnOrder" Type="Int16" />
            <asp:Parameter Name="ReorderLevel" Type="Int16" />
            <asp:Parameter Name="Discontinued" Type="Boolean" />
            <asp:Parameter Name="Inactive" Type="String" />
            <asp:Parameter Name="ProductID" Type="Int32" />
        <asp:Parameter Name="ProductName" Type="String" />
        <asp:Parameter Name="SupplierID" Type="Int32" />
        <asp:Parameter Name="CategoryID" Type="Int32" />
            <asp:Parameter Name="QuantityPerUnit" Type="String" />
            <asp:Parameter Name="UnitPrice" Type="Decimal" />
            <asp:Parameter Name="UnitsInStock" Type="Int16" />
            <asp:Parameter Name="UnitsOnOrder" Type="Int16" />
            <asp:Parameter Name="ReorderLevel" Type="Int16" />
            <asp:Parameter Name="Discontinued" Type="Boolean" />
            <asp:Parameter Name="Inactive" Type="String" />

        <asp:Button ID="ASPda" runat="Server" Text="Deactivate ASP" OnClick="Deactivate"/>


Specific button I want to run the Deactivate command.

<asp:Button ID="ASPda" runat="Server" Text="Deactivate ASP" OnClick="Deactivate"/>

Let's take the example below:

    public void Configure(IApplicationBuilder app)
        RequestDelegate a = async (ctx) =>
            if (1 == 1)
                ctx.Response.StatusCode = 500;
                await ctx.Response.WriteAsync("I'm done");
        RequestDelegate b = async (ctx) => await ctx.Response.WriteAsync("Please don't hit this"); ;

        RequestDelegate c = a += b;


As the two funcs have been concatenated with the c variable both will be executed. What I'm looking at trying to do is signal in the first func that I don't want the second func to be executed and it should return the HttpResponse as it is in the first func.

Obviously in this simple example I could use a global boolean etc but that's not what I'm getting at, it's really if you have 2 funcs concatenated maybe from 2 separate libs is there a way to make the 2nd func not execute when you have no control over the execution, all you know is that the funcs will be executed by something else you have no control over.

I have embedded a user control in an aspx page:

<%@ Page Title="" Language="VB" MasterPageFile="~/Default.master" AutoEventWireup="false" CodeFile="Stuff.aspx.vb" Inherits="Stuff_aspx" %>

<%@ Register Src="~/Thing.ascx" TagPrefix="uc" TagName="Thing" %>
<asp:Content ID="Content1" ContentPlaceHolderID="cphBody" runat="Server">
<uc:Thing runat="server" ID="Thingy" />

The code behind for that page references the user control:

Partial Class Stuff_aspx
    Inherits System.Web.UI.Page

    Private Sub btnMakeItSo_Click(sender As Object, e As EventArgs) Handles btnMakeItSo.Click        
    End Sub

End Class

That user control has a couple of public methods:

Partial Class Thing
    Inherits System.Web.UI.UserControl

    Public Sub DoStuff(Optional Attempts As Integer = 0)
        Dim GitErDone As Boolean = False
        While Not GitErDone
            Attempts += 1
            If Attempts = 1000 Then
                GitErDone = True
            End If
        End While
    End Sub

    Public Sub LoadThings()
    End Sub

End Class

When I "Find All References" on the "DoStuff" method in the UserControl, it only shows the reference inside "LoadThings" and does not catch the reference in the codebehind of the Stuff.aspx page.

Similarly, if I rename the method, the changes are only applied inside the user control.

How can I correct this behavior such that all references are found/updated appropriately?

Why is it unable to find the reference outside the control?

im trying to learn ajax with jquery but there is something i dont understand. As you can see in the code below, when we call the onSuccess function it takes no arguments, but the function itself does take the response. The code is working, but how and why? and if i want to send another parameter to the success function how do i do it?

    type: "POST",
    //getListOfCars is my webmethod   
    url: "WebService.asmx/getListOfCars", 
    data: jsonData,
    contentType: "application/json; charset=utf-8",
    dataType: "json", // dataType is json format
    success: OnSuccess,
    error: OnErrorCall

****function OnSuccess(response) {

So I've been working on a simple asp.net application this week. And today I had a problem with a razor view not returning anything to my controller method. The view had to return several objects in a List<>.

I finally got it working by passing a list of objects to the view and looping through them with a 'for' loop. I also tried it today with a foreach loop but that didn't work.

I've got the following GET method that passes a list of empty objects to the view:

// GET: MpSwitches/CreateSeveral
    public ActionResult CreateSeveral()
        var mpSwitches = new List<MpSwitch>
            new MpSwitch() {IpAdress = "1"},
            new MpSwitch() {IpAdress = "2"},
            new MpSwitch() {IpAdress = "3"},
            new MpSwitch() {IpAdress = "4"},
            new MpSwitch() {IpAdress = "5"}
        // Check if the user gets redirected to this method because of a First Time Startup.
        if (TempData["RedirectFirstTimeStartup"] != null)
            ViewBag.FirstTime =
                "Je bent doorgestuurd naar deze pagina omdat er nog geen MP-switches in de database staan.";
            return View(mpSwitches);
        return View(mpSwitches);

Then there is the View:

@model List<WebInterface.Models.MpSwitch>
    ViewBag.Title = "Create several";
<h2>Create several</h2>

@using (Html.BeginForm())

    <div class="form-horizontal">
        @if (ViewBag.FirstTime != null)
            <div class="alert-warning">
                <b>Opgelet! </b>@ViewBag.FirstTime
        @for (int i = 0; i < Model.Count; i++)
            <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger" })
            <div class="form-group">
                @Html.LabelFor(model => model[i].IpAdress, htmlAttributes: new { @class = "control-label col-md-2" })
                <div class="col-md-10">
                    @Html.EditorFor(model => model[i].IpAdress, new { htmlAttributes = new { @class = "form-control" } })
                    @Html.ValidationMessageFor(model => model[i].IpAdress, "", new { @class = "text-danger" })
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />

    @Html.ActionLink("Back to List", "Index")

My question is: Why doesn't this same code work with a 'foreach' instead of the 'for' loop?

The code that isn't working currently:

    @foreach (var item in Model)
        <hr />
            @Html.ValidationSummary(true, "", new { @class = "text-danger"})
            <div class="form-group">
            @Html.LabelFor(modelItem => item.IpAdress, htmlAttributes: new { 
    @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(modelItem => item.IpAdress, new { 
    htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(modelItem => item.IpAdress, "", new 
    { @class = "text-danger" })

Now when using the foreach loop the following controller method doesn't get a parameter (the parameter is null).

    // POST: MpSwitches/CreateSeveral
    // To protect from overposting attacks, please enable the specific 
    properties you want to bind to, for 
    // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
    public ActionResult CreateSeveral([Bind(Include = 
    "Id,IpAdress,LastSyncDateTime")] List<MpSwitch> mpSwitches)
        if (ModelState.IsValid)
            foreach (var mpSwitch in mpSwitches)
            return RedirectToAction("Index");
        return View(mpSwitches);

And i get the following error: Link to image of my error

I am trying to change the view that on of my controllers points to however this is not picking up the amendment. The following is the code I am trying to use;

// GET: UserDemographics/Create
public ActionResult Create()
    return View("Manage");

And my views folders look like below:

enter image description here

My understanding is that View tries to check for the same name as the method but I may be wrong. Any help would be appreciated.

This question already has an answer here:

I am using the following for displaying the date field in my razor view form:

@Html.TextBoxFor(m => m.LectureDate, "{0:dd/MM/yyyy}")

Which should allow the date format to be displayed in format 21/04/2017, which is what is being supplied through JQuery DatePicker, but after it is set to this by datepicker and the form is submitted, the MVC Validation throws error and does not allow to submit the form.

I have tried applying <globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="en-GB" uiCulture="en-GB" /> in Web.Config. I have tried adding the data annotations attributes specified in the answers suggested.

And I have also tried specifying the format in the Html Helper only. But, still the MVC throws error and does not submit the form.

How can this be done?

Hopefully I am making myself clear. I have an area in my mvc project with two shared layouts _Application.cshtml (For Areas) _Layout.cshtml (For non-areas)

Reports and Favourites are for the area controller.
Roles and Users are for the default namespace controllers.

<li>@Html.ActionLink("Reports", "Reports", "Home")</li>
<li>@Html.ActionLink("Favourites", "Favourites", "Home")</li>
<li>@Html.ActionLink("System Roles", "Roles", "Support",new { Area = "" },  htmlAttributes: new { title = "System Roles" }) </li>
<li>@Html.ActionLink("Users", "Users", "Support", new { Area = "" },   htmlAttributes: new { title = "Users" })</li>

Defined in the Roles and Users View I am defining a different shared layout. That do not have links to Reports and Favourites (just totally different navigation menu).

Is it possible to assign the layout of Roles and Users to my _Application shared layout without losing the ability to call the actions from the default namespace controller?

if (this.ViewContext.RouteData.DataTokens["Area"] != null)    {
    Layout = "~/Views/Shared/_Application.cshtml";
    Layout = "~/Views/Shared/_Layout.cshtml";

I've tried this but the DataToken never receives an Area route because it's not defined.

Edit: Sorry I am having trouble describing the issue (even with co-workers too...)

Area "Procurement": Controller : "Home" has three views Index, Reports and Favourites. Navigation Menu (_Applicaiton.cshtml) is custom to the Procurement Area only

Non Area : Controller "Support" has two view Roles and Users. Navigation Menu (_Layout.cshtml) is generic that contains links to navigate to other Areas of the project

The Action Links above reside in the Index View. If I click Reports or Favourites, it will navigate me to ApplicationName/Procurement/Home/Reports or ApplicationName/Procurement/Home/Favourites

If I click Roles or Users, it will navigate me to ApplicationName/Support/Roles or ApplicationName/SupportUsers

Because of how I have defined the layouts for Roles and Users, the navigation menu defaults back to the generic one instead of displaying the one specific to Procurement Area.

I am looking to see if it is possible that when I click Roles or Users for the navigation menu to stay on the Procurement Layout and reference the same Support controller. I don't want to have to create the Roles and Users page for each Area that I am creating.

hope all is well, I want to get the method private ProductStatusModel GetProductStatusModelFromOrganisation(Guid id) from class OrganisationService.cs in the namespace CLAPICRMDataService.Core, in a different namespace this time called namespace CategoryItemToOrgLinker in class StatusAttainment Email.

The method I want to call is below:

private ProductStatusModel GetProductStatusModelFromOrganisation(Guid id)

ProductStatusModel productStatus = new ProductStatusModel
AchievedLevel = 0,
CurrentLevel = 1,
CurrentStatus = string.Empty,
TargetLevel = 1,
TargetStatus = string.Empty

List<CatalogItemToOrganisationLinker> results = new List<CatalogItemToOrganisationLinker>();

results = Queries.CategoryItemToOrganisationLinker                        .GetAchievedCatalogProductLevel(id).FetchEntities<CatalogItemToOrganisationLinker>(connection.OrganizationService).NullToEmpty();

catch (Exception)
results = null;
if (results != null && results.Any())
var productStatusProxy = results.First();

mm_supplierstatus? achievedStatus = productStatusProxy.AchievedCatalogProductStatus;

var topPriorityStatus = productStatusProxy.TopPriorityStatus;
var achievedProductItemStatus = productStatusProxy.AchievedCatalogProductStatus;

AliasedValue currentLevelAlias = productStatusProxy.Entity.GetAttributeValue<AliasedValue>("catlogproduct.mm_priority");

int currentLevel = (int?)currentLevelAlias?.Value ?? 1, // set current level, defaults to 1 (Freemium) if not set.achievedLevel = currentLevel; 

if (achievedStatus.HasValue)
if (achievedLevel > 1 && achievedStatus.Value != mm_supplierstatus.Verified)
achievedLevel -= 1;

productStatus = new ProductStatusModel
TargetStatus = topPriorityStatus.ToDescription() ?? string.Empty,

CurrentStatus = achievedProductItemStatus.ToDescription() ?? string.Empty,
CurrentLevel = currentLevel,
AchievedLevel = achievedLevel

I want to call it here:

public override void Execute(CodeActivityContextWrapper context)
IOrganizationService service = context.GetService();
EntityReference CatItemReference = CatalogItemToOrgLinker.GetFromWrapper<EntityReference>(context, nameof(CatalogItemToOrgLinker));

Var catItemOrgLinker = service.FetchEntity<CatalogItemToOrganisationLinker>(CatItemReference);

if (catItemOrgLinker == null)
throw new InvalidPluginExecutionException("Unable to locate Catalog Item To Organisation Linker");

//Reference product status model here. CALL IT HERE

I have a JavaScript function that I wrote and embedded in an .aspx page. I declared variables at the top of the function that access ConfigurationManager.AppSettings and also the sessionState tag as follows:

var Value1 = "<%= System.Configuration.ConfigurationManager.AppSettings["Value1"].ToString()%>";
var Value2 = "<%= Session.Timeout %>";

This function has been working just fine. I've realized that I will need to use the function across four other pages so I decided to move it to an external JavaScript file. According to this question and accepted answer...

Accessing ConfigurationManager.AppSettings in Java script

...external JavaScript files do not evaluate code inside of these "server-side code" tags, therefore, values from the web.config file must be passed from the .aspx page as parameters. I moved the function to an external JavaScript file and call the function like this:

<script src="Scripts/JavaScript.js" type="text/javascript">    
    var Value1 = "<%= System.Configuration.ConfigurationManager.AppSettings["Value1"].ToString()%>";
    var Value2 = "<%= Session.Timeout %>";
    externalFunction(Value1, Value2)

The external JavaScript functions begins as follows:

function externalFunction(Value1_, Value2_) {

    var Value1 = Value_1;
    var Value2 = Value_2;



As I debug the JavaScript function, the arguments themselves are undefined. What am I missing here?