I'm trying to integrate ASP.Net 5.0 with AngularJS with Active Directory, but constantly receiving 404 error when accessing "/api/Account/Ping".

ui-router set up:

app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider',
    function ($stateProvider, $urlRouterProvider, $locationProvider) {


            enabled: true,
            requireBase: false

        .state('stateIndex', {
                    url: '/',
                    templateUrl: '/templates/list.html',
                    controller: 'dashListController'     
        .state('stateList', {
                    url: '/list',
                    templateUrl: '/templates/list.html',
                    controller: 'dashListController'
        }).state('stateDashboard', {
                    url: '/dashboard',
                    templateUrl: '/templates/dashboard.html',
                    controller: 'dashboardController'
        .state('stateWidgetsList', {
                    url: '/widgetsList',
                    templateUrl: '/templates/widgetsList.html',
                    controller: 'widgetsListController',
                    resolve: {
                        authentication: ['$http', function ($http) {
                            return $http.get('api/Account/Ping');


public class AccountController : ApiController
    [HttpGet, Route("Ping")]
    public IHttpActionResult Ping()
        return Ok();


public class WidgetsController : Controller
    private readonly PMSContext _dbContext;

    public WidgetsController(PMSContext dbContext)
        _dbContext = dbContext;

    public IEnumerable<Widget> Get()
        return _dbContext.Widgets;

I'm using interceptors to route it to login screen., but every time I'm trying to access /widgetsList I get 404 error. What am I missing here?

I'm writing a web server application which needs to access a network drive. I have Windows Authentication and ASP.NET impersonation enabled. I can display the impersonated user, but whenever I attempt to open a directory in ASP.NET, it says access to the directory is denied. I've disabled anonymous authentication. Do I have to register the regular domain accounts in any of the Permissions Group on the Windows Server 2008 R2 in order to get access to the network drive? Modifying the network drive to change it's permissions is not an option.

Problem Statement:

I'm using custom validation attribute RequiredIf to validate some fields in my MVC-Razor application.Everything was working fine.But recently we noticed, application taking too much time to respond after spending some time with the application.When contacted Microsoft support team,they suggested to change the requiredIf, as the current one is making the application to respond slowly.So we modified the old RequiredIf with the new one.But the current RequiredIf is not triggering the model data annotations which were triggering earlier.What's wrong in the new RequiredIf attribute.

Any suggestion/answer would be highly appreciated.??

Old RequiredIf Code:

Codeproject link for more info: Codeproject

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
    public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
        private readonly string defaultErrorMessageFormatString = "The {0} is required";
        public List<string> DependentProperties { get; private set; }
        public List<string> DependentValues { get; private set; }
        public string Props { get; private set; }
        public string Vals { get; private set; }
        public string RequiredFieldValue { get; private set; }

        //To avoid multiple rules with same name
        public static Dictionary<string, int> CountPerField;
        //Required if you want to use this attribute multiple times
        private readonly object typeId = new object();
        public override object TypeId
            get { return typeId; }

        public RequiredIfAttribute(string dependentProperties,
               string dependentValues = "", string requiredValue = "val")
            if (string.IsNullOrWhiteSpace(dependentProperties))
                throw new ArgumentNullException("dependentProperties");
            string[] props = dependentProperties.Trim().Split(',');
            if (props != null && props.Length == 0)
                throw new ArgumentException("Prameter Invalid:DependentProperties");

            if (props.Contains("") || props.Contains(null))
                throw new ArgumentException("Prameter Invalid:DependentProperties," +
                          "One of the Property Name is Empty");

            string[] vals = null;
            if (!string.IsNullOrWhiteSpace(dependentValues))
                vals = dependentValues.Trim().Split(',');

            if (vals != null && vals.Length != props.Length)
                throw new ArgumentException("Different Number " +
                      "Of DependentProperties And DependentValues");

            DependentProperties = new List<string>();
            Props = dependentProperties.Trim();
            if (vals != null)
                DependentValues = new List<string>();
                Vals = dependentValues.Trim();

            if (requiredValue == "val")
                RequiredFieldValue = "val";
            else if (string.IsNullOrWhiteSpace(requiredValue))
                RequiredFieldValue = string.Empty;
                defaultErrorMessageFormatString = "The {0} should not be given";
                RequiredFieldValue = requiredValue;
                defaultErrorMessageFormatString =
                        "The {0} should be:" + RequiredFieldValue;

            if (props.Length == 1)
                if (vals != null)
                    ErrorMessage = defaultErrorMessageFormatString +
                                   @", When " + props[0] + @" is ";
                    if (vals[0] == "val")
                        ErrorMessage += @" given";
                    else if (vals[0] == "")
                        ErrorMessage += @" not given";
                        ErrorMessage += vals[0];
                    ErrorMessage = defaultErrorMessageFormatString +
                                   @", When " + props[0] + @" is given";
                if (vals != null)
                    ErrorMessage = defaultErrorMessageFormatString +
                                   @", When " + dependentProperties + @" are: ";
                    foreach (string val in vals)
                        if (val == "val")
                            ErrorMessage += @"AnyValue,";
                        else if (val == "")
                            ErrorMessage += @"Empty,";
                            ErrorMessage += val + @",";
                    ErrorMessage = ErrorMessage.Remove(ErrorMessage.Length - 1);
                    ErrorMessage = defaultErrorMessageFormatString + @", When " +
                                   dependentProperties + @" are given";

        protected override ValidationResult IsValid(object value,
                           ValidationContext validationContext)
            //Validate Dependent Property Values First
            for (int i = 0; i < DependentProperties.Count; i++)
                var contextProp =
                var contextPropVal = Convert.ToString(contextProp.GetValue(
                                             validationContext.ObjectInstance, null));

                var requiredPropVal = "val";
                if (DependentValues != null)
                    requiredPropVal = DependentValues[i];

                if (requiredPropVal ==
                       "val" && string.IsNullOrWhiteSpace(contextPropVal))
                    return ValidationResult.Success;
                else if (requiredPropVal == string.Empty &&
                    return ValidationResult.Success;
                else if (requiredPropVal != string.Empty && requiredPropVal !=
                            "val" && requiredPropVal != contextPropVal)
                    return ValidationResult.Success;

            string fieldVal = (value != null ? value.ToString() : string.Empty);

            if (RequiredFieldValue == "val" && fieldVal.Length == 0)
                return new ValidationResult(string.Format(
                           ErrorMessageString, validationContext.DisplayName));
            else if (RequiredFieldValue == string.Empty && fieldVal.Length != 0)
                return new ValidationResult(string.Format(
                           ErrorMessageString, validationContext.DisplayName));
            else if (RequiredFieldValue != string.Empty && RequiredFieldValue
                     != "val" && RequiredFieldValue != fieldVal)
                return new ValidationResult(string.Format(ErrorMessageString,

            return ValidationResult.Success;

        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(
               ModelMetadata metadata, ControllerContext context)
            int count = 0;
            string key = metadata.ContainerType.FullName + "." + metadata.GetDisplayName();

            if (CountPerField == null)
                CountPerField = new Dictionary<string, int>();

            if (CountPerField.ContainsKey(key))
                count = ++CountPerField[key];
                CountPerField.Add(key, count);

            yield return new RequiredIfValidationRule(string.Format(ErrorMessageString,
                  metadata.GetDisplayName()), RequiredFieldValue, Props, Vals, count);

    public class RequiredIfValidationRule : ModelClientValidationRule
        public RequiredIfValidationRule(string errorMessage, string reqVal,
               string otherProperties, string otherValues, int count)
            int i = 0;

            while (count > 26)
                count -= 26;

            var tmp = count == 0 ? "" : Char.ConvertFromUtf32(96 + count);
            while (i > 0)
                tmp += tmp;

            ErrorMessage = errorMessage;
            ValidationType = "requiredif" + tmp;
            ValidationParameters.Add("reqval", reqVal);
            ValidationParameters.Add("others", otherProperties);
            ValidationParameters.Add("values", otherValues);

New RequiredIf Code:

Stackoverflow link for more info : Stackoverflow

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = true)]
public class RequiredIfAttribute : ValidationAttribute, IClientValidatable
    private String PropertyName { get; set; }
    private Object DesiredValue { get; set; }
    private readonly RequiredAttribute _innerAttribute;

    public RequiredIfAttribute(String propertyName, Object desiredvalue)
        PropertyName = propertyName;
        DesiredValue = desiredvalue;
        _innerAttribute = new RequiredAttribute();

    protected override ValidationResult IsValid(object value, ValidationContext context)
        if (context.ObjectInstance.GetType().GetProperty(PropertyName) != null)
            var dependentValue =
                context.ObjectInstance.GetType().GetProperty(PropertyName).GetValue(context.ObjectInstance, null);

            if (dependentValue != null && dependentValue.ToString() == DesiredValue.ToString())
                if (!_innerAttribute.IsValid(value))
                    return new ValidationResult(FormatErrorMessage(context.DisplayName), new[] { context.MemberName });
        return ValidationResult.Success;

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
        var rule = new ModelClientValidationRule
            ErrorMessage = ErrorMessageString,
            ValidationType = "requiredif",
        // ReSharper disable once PossibleNullReferenceException
        rule.ValidationParameters["dependentproperty"] = (context as ViewContext).ViewData.TemplateInfo.GetFullHtmlFieldId(PropertyName);
        rule.ValidationParameters["desiredvalue"] = DesiredValue is bool ? DesiredValue.ToString().ToLower() : DesiredValue;

        yield return rule;


I have view, which has it's own controller and it includes libraries such as bootstrap, jquery,.. It's path is "Views/MyView" Now I have another view: "Views/MainView", which also includes the same libraries. Can I include MyView inside this view since it is not in Shared folder? And frameworks will be loaded twice I guess? But is is the only way that view will have everywhere all needed libraries.

My Dynamic Pivot Query is as follows

    var sql_ovrd = @"DECLARE @out VARCHAR(MAX)
                SELECT @out = COALESCE(@out+'],[' ,'') + Hospital_Name
                FROM Hospitals
                SELECT @out = '['+@out+ ']'

                DECLARE @sql varchar(1000)
                SET @sql = '
                SELECT * FROM        
                    FROM    OVRREPORTED 
                            INNER JOIN OVRCategory ON OVRReported.OVRCatID = OVRCategory.OVRCatID
                            INNER JOIN Hospitals ON OVRReported.Hospital_ID = Hospitals.Hospital_ID
                ) AS T 

                PIVOT (COUNT(OVRCAT) FOR Hospital IN ('+@out+')) AS P'
                EXEC (@sql)"; //
var ovrd_data = db.Query(sql_ovrd,3,2015);

This keeps giving me error message that "Must declare the scalar variable "@0". Am I doing something silly?

The web grid I am trying to create works fine when I remove "AND MONTH(OVRREPORTED.DATERECEIVED) =@0 AND YEAR(OVRREPORTED.DATERECEIVED)=@1" from the Where Clause. Also when I try to execute directly on the sql studio as "AND MONTH(OVRREPORTED.DATERECEIVED) =3 AND YEAR(OVRREPORTED.DATERECEIVED)=2015" it is working perfectly.

Is it not possible to pass variables from Web Pages Razor syntax to a dynamic query?

I have created a custom routing and it works fine at first click, but when I tried to click it give me a 404 error. I notice when I hover on the link the url path goes back to the controller name. Why is that? How to fix this?

Here is the custom routing I created:

   new { action = "Index", detail = UrlParameter.Optional }
).DataTokens = new RouteValueDictionary { { "__RouteName", "Project" } };

Here is the View Page:

@model string
    var routeValues = new { id = Model, area = "" };
    @Html.NavLink(NavigationName, "ActionName", "ControllerName", "glyphicon glyphicon-calendar", routeValues, isLeftNavLink: true)

Here is the Controller Action:

[RequiredId, Route("project/{id}/subtype/samplename")]
public ActionResult Index(int id) {
   return View();

Now this works. But whenever I'm inside of the View page, and try to click na navigation bar to go to this page again, it give me an 404 error. and the route goes back to the name of the controller. Any solution that I can do to fix this?

I have some bool values in my model and

@Html.DisplayFor(model => model.myBool)

displays my checkbox in my index/delete.cshtml without having to care that it's a checkbox or something else - that's nice, but ...

The checkbox is displayed disabled - that's ok in terms of having them readonly, but the style of disabled checkboxes is too lightgrey and the readability isn't perfect.

So what would you suggest?

My preferred way would be some CSS, but something like

input[type=checkbox]:disabled { "inherit the style of enabled checkboxes" }

isn't possible in CSS (to my knowledge) and

input[type=checkbox]:disabled { ... }

doesn't seem to have any effect. Firebug shows that the syntax is right and the code should be used, but whatever I write in there, e.g. background-color: red is ignored (at least in Firefox, didn't test on other browsers).

Other possible solutions: having images - seems very ugly to me, CSS is the way for styling (at least it should be).

So far, my workaround is using

@Html.EditorFor(model => model.myBool)

and prevent clicks on it by adding a jquery/javascript (you may want to adapt the selector in case you have checkboxes in your View that you want to use for more than displaying purposes)

$("input[type=checkbox]").click(function () { return false; });

It displays the checkboxes as I want them, but I'd prefer some direct way using some options in the @Html.Display(...) or using CSS instead of Javascript.

Any suggestions?

I am trying to bind dropdownlist with mysql database column but not able to achieve it. Getting this error

ERROR :  BC30451: 'fetchOrder' is not declared. It may be inaccessible due to its protection level.


<asp:ListView ID="driversData" runat="server" DataKeyNames="DriverID" >
                                        <asp:DropDownList ID="fetchOrder" runat="server">

                                <div style="text-align: center" class="list-item-box">
                                    <strong>Oops...No Record Found...</strong>
                                <ul id="itemPlaceholderContainer" runat="server" style="margin: 0; padding: 0">
                                    <li runat="server" id="itemPlaceholder" />
                                <div style="margin: 0; padding: 0">
                                    <asp:DataPager ID="DataPager1" runat="server" PageSize="50" PagedControlID="driversData"
                                            <asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True" ShowLastPageButton="True"
                                                ButtonCssClass="last" />


Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        addDriver.Visible = False
            ViewState("Data") = ""
            Using con As New MySqlConnection(constr)
                Using cmd As New MySqlCommand("SELECT * FROM addDriver ")
                    Using sda As New MySqlDataAdapter()
                        cmd.Connection = con
                        sda.SelectCommand = cmd
                        cmd.CommandTimeout = 0
                        Using dt As New DataTable()
                            ViewState("Data") = dt
                            driversData.DataSource = dt

                        End Using
                    End Using
                End Using
            End Using

            'countResult.Text = (" " & schoollists.Items.Count & " " & board.Text & " Schools Found in " & area.Text & " ")

        Catch ex As Exception
        End Try

        If Not Me.IsPostBack Then
            Using con As New MySqlConnection(constr)
                Using cmd As New MySqlCommand("SELECT Bid FROM newBooking")
                    cmd.CommandType = CommandType.Text
                    cmd.Connection = con
                    fetchOrder.DataSource = cmd.ExecuteReader()
                    fetchOrder.DataTextField = "Bid"
                End Using
            End Using
            fetchOrder.Items.Insert(0, New ListItem("--Select Customer--", "0"))
        End If
    End Sub

If I don't use list view & apply same code then it works fine. I guess there is some addition needed top apply it in listview. Can anybody help me to achive it..

.aspx file code

<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
    <div style="background-color:lightgray;font-family:'Comic Sans MS' ">
  <br />
    <h2 style="text-align:center;"> CONTACT <b><span style="color:red">L</span>EA<span style="color:darkgreen">P</span></b> DRIVING SCHOOL</h2>
        <br />
    <fieldset style="align-content:center; color:lightgray;text-align:center ">
      <br /> <br />  
        <asp:Label ID="Label2" runat="server" Text="Name" ForeColor="Black"></asp:Label><br />
        <asp:TextBox ID="TextBox1" runat="server" size="25"  >  </asp:TextBox> <%--<asp:RequiredFieldValidator
            ID="rfvName" runat="server" ErrorMessage="Please enter Name"
            ControlToValidate="TextBox1" Display="Dynamic" ForeColor="#FF3300"
            SetFocusOnError="True"></asp:RequiredFieldValidator>       --%>                                                                                               <br /> <br />
        <asp:Label ID="Label3" runat="server" Text="mobile number" ForeColor="Black"></asp:Label> <br />
          <asp:TextBox ID="TextBox2" runat="server" size="25" ForeColor="Black"></asp:TextBox>  <%-- <asp:RequiredFieldValidator
            ID="RequiredFieldValidator2" runat="server" ErrorMessage="Please enter Number"
            ControlToValidate="TextBox2" Display="Dynamic" ForeColor="#FF3300"
            SetFocusOnError="True"></asp:RequiredFieldValidator>                              --%>                      <br /> <br />
        <asp:Label ID="Label4" runat="server" Text="Email" ForeColor="Black"></asp:Label> <br />
        <asp:TextBox ID="TextBox3" runat="server"  size="25" ></asp:TextBox>   <%--<asp:RequiredFieldValidator ID="rfvEmailId" runat="server"
            ControlToValidate="TextBox3" Display="Dynamic"
            ErrorMessage="Please enter Email Id" ForeColor="Red" SetFocusOnError="True"></asp:RequiredFieldValidator>
        <asp:RegularExpressionValidator ID="rgeEmailId" runat="server"
            ControlToValidate="TextBox3" Display="Dynamic"
            ErrorMessage="Please enter valid email id format" ForeColor="Red"
            ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"></asp:RegularExpressionValidator>    --%>                                                                      <br /> <br />
        <asp:Label ID="Label5" runat="server" Text="City" ForeColor="Black"></asp:Label> <br />
         <asp:TextBox ID="TextBox4" runat="server" size="25" ></asp:TextBox>                <br /> <br />
        <asp:Label ID="Label6" runat="server" Text="Message" ForeColor="Black"></asp:Label> <br />
        <asp:TextBox id="TextArea1" TextMode="multiline" Columns="27" Rows="8" runat="server" />  <br /> <br />
    <asp:Button ID="Button1" runat="server" Text="Submit" Font-Bold="true" BackColor="Green" Width="83px" height="37px" OnClick="Button1_Click" />    &nbsp &nbsp &nbsp
        <asp:Button ID="Button2" runat="server" Text="Reset"  Font-Bold="true" BackColor="red" Width="83px" height="37px"/>

        <br /> <br />
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
<br />
        <br />

.css file code

  protected void Button1_Click(object sender, EventArgs e)
       // string connstring=ConfigurationManager.ConnectionStrings["yourconnstringInWebConfig"].ConnectionString;
     //   SqlConnection con = new SqlConnection();
       // SqlConnection con = new SqlConnection();
       // con.ConnectionString = "Data Source=ADMIN;Initial Catalog=contact;Integrated Security=True";

        string insertSQL="INSERT INTO dbo.contct("  ;
        insertSQL += "name,number,email,city,msg)";
        insertSQL += "VALUES ('";
        insertSQL += TextBox1.Text + "','";
        insertSQL += TextBox2.Text + "','";
        insertSQL += TextBox3.Text + "','";
        insertSQL += TextBox4.Text + "','";
        insertSQL += TextArea1.Text + "','";

       SqlConnection con = new SqlConnection("Data Source=ADMIN;Initial Catalog=contact;Integrated Security=True");
        SqlCommand cmd = new SqlCommand(insertSQL,con);
        int added = 0;
      try  {
          added = cmd.ExecuteNonQuery();
          Label1.Text = added.ToString() + "successfuly your information is submitted thank you!!";
      catch (Exception er)
          Label1.Text = "error while inserting record";
          Label1.Text = er.Message;



these are two file code form and sql query to insert value into form when user submits button it should add value to the table i created in sql database but no data is going there no value is being submitted i have tried no. of times but its not working plz help me out in this

I have a small widgetbox on my webpage. This widgets box contains these elements:

<table class="absence-widget-table">
        <td class="absence-widget-left">
            <i class="fa fa-chevron-left" title="Next" aria-describedby="ui-tooltip-1"></i>
        <td class="absence-widget-center" id="absence-date-container">
            @Html.Partial(MVC.ActivityWidget.Views.Partials.MyActivityAbsenceDateChanger, Model)
        <td class="absence-widget-right">
            <i class="fa fa-chevron-right" title="Previous"></i>

And these elements have these styles in my css file:

.center-absence-widget-left {
    position: relative;
    left: 604px;
    padding-top: 13px;
    padding-bottom: 10px;
    cursor: pointer;

.center-absence-widget-right {
    position: relative;
    left: 640px;
    padding-top: 13px;
    padding-bottom: 10px;
    cursor: pointer;

.center-absence-widget-center {
    position: relative;
    left: 620px;
    padding-top: 10px;
    padding-bottom: 10px;
    text-align: center;
    white-space: nowrap;
    width: 15%;

what i want to know is how do i add responsive design for these elements so when the page is not opened in a screen with less resolution, then the html elements responds to that and adjusts to it?

can anyone help with this ?

I want to know how to disable pasts date in calendar extendar in asp.net Code behind. I I want to do it code behind without using java scripts.

my asp.net code is like this:

 <asp:Label ID="LblSubid" runat="server" Text='<%#Eval("ID") %>' Visible="false"></asp:Label>
                     <asp:LinkButton ID="LblSubName" runat="server" Text='<%#Eval("SottocatENG")%>' CommandName="Category"><%#Eval("SottocatENG")%></asp:LinkButton>
                     <asp:Label ID="LblSotta" runat="server" Text=' <%#Eval("SottocatENG")%>' Visible="false"></asp:Label>
                  <asp:Label ID="LblKey" runat="server" Text='<%#Eval("KeywordDensityENG") %>' Visible="false"></asp:Label>

it is working fine.. when i click on that link button than it will call a function and store some value and redirect to another page...

PROBLEM is when i hover a mouse on it.. at bottom left of browser its showing javascript:javascript:__doPostBack('rptMenu$ctl00$LblCatName',''); i want to show link instead of this like: example.com ..

so i was thinking to put anchor tag here like:

      <a href="abc.com">
                   <asp:Label ID="LblSubid" runat="server" Text='<%#Eval("ID") %>' Visible="false"></asp:Label>
                     <a ID="LblSubName" runat="server" Text='<%#Eval("SottocatENG")%>' CommandName="Category"><%#Eval("SottocatENG")%></a>
                     <asp:Label ID="LblSotta" runat="server" Text=' <%#Eval("SottocatENG")%>' Visible="false"></asp:Label>
                  <asp:Label ID="LblKey" runat="server" Text='<%#Eval("KeywordDensityENG") %>' Visible="false"></asp:Label></a>

but its not working...

I have tried this: Click here

but its not working in default setting..

How to achieve this??? Thank you

GridView Table (Asp. Net)

CstID Name Manufacturer Model

1 Patel Hyundai,Toyota(DropDown List) Hyundai1, Hyundai1, Toyota1 Toyota(DropDown List)

If i select "Hyndai" only show "Hyundai models", If i select "Toyota" only shown "Toyota Models".

I am trying to use Highcharts to see if it will work for me but I can't get anything to load.

I downloaded the samples but they don't work with Visual Studio 2010, I downloaded a trial of Visual Studio 2013 and i get the error 'HTTP Error 500.0 - Internal Server Error'

I have tried several very simple sample codes but with VS2010 but I keep getting a blank screen.

I really need a starting point to learn how to use Highcharts to see how they could improve my current web software that uses very basic google charts with Json.

This question already has an answer here:

I am new to MVC.

I have the following file structure:

  • _Layout.cshtml -> Layout page.
  • News.cshtml -> Page that renders inside the Layout to show news on the page.
  • _Newsletter.cshtml -> partial view that shows a form for sign newsletters.
  • Models -> Where the fields necessary to show the news are defined.
  • Repository -> Where I define a method to get the news from the database.

The code:



@if (ViewBag.NewsletterSuccedd != null)
       window.scrollTo(0, document.body.offsetHeight)
else {@Html.Partial("~/Views/Shared/_Newsletter.cshtml")}


@foreach(var item in ViewBag.News)
      <img src="/Content/Images/news/@item.Image" alt="">


@model APP.Models.Newsletters

@using (Ajax.BeginForm(new AjaxOptions() { Url = "/Newsletters/" }))
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

    @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control", @placeholder = "Name" } })
    @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

    @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class = "form-control", @placeholder = "E-mail" } })
    @Html.ValidationMessageFor(model => model.Email, "", new { @class = "text-danger" })

<input type="submit" value="Send" class="btn btn-default" />



namespace APP.Models
    public class NewsForWP
        public string Title { get; set; }
        public string Body { get; set; }
        public DateTime Date { get; set; }
        public string Image { get; set; }


namespace APP.Models
    public class Repository
        public List<NewsForWP> getNews()
            List<NewsForWP> nfwp = new List<NewsForWP>();

            using (AppIdentityDbContext db = new AppIdentityDbContext())
                var news = from neww in db.News select neww;

                foreach (News item in news)
                    nfwp.Add(new NewsForWP { Title = item.Title, Body = item.Body, Date = item.NewsDate, Image = item.NewsImageResized });

            return nfwp;



Repository _repository = new Repository();

public ActionResult News([Bind(Include = "NewslettersID,Name,Email")] Newsletters newsletters)
    return View(Adiciona(newsletters));

private Newsletters Adiciona(Newsletters newsletters)
    if (ModelState.IsValid)
        ViewBag.NewsletterSuccedd = "You have successfully subscribed to our newsletters.";

    return newsletters;

public ActionResult News()
    ViewBag.News = _repository.getNews();
    return View();

The issue here for me is, the newsletter is in the layout and the news are in another page that is rendered by the Renderbody(). If both in the same page I would try to use Tuple, but in this case I don't know what to do.

The news are displayed correctly, but when try to subscribe to the newsletters, i get the following error:

Server Error in '/' Application.

Object reference not set to an instance of an object.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error: 

Line 11:                 <div id="blogmasonry">
Line 12:                     <div class="row filterable">
Line 13:                         @foreach(var item in ViewBag.News)
Line 14:                         {

Does someone know what should I do here? Thanks in advance.

It is possible to use app keys for all the connection string inputs and read those on connection string like bellow

<add name="DefaultConnection" connectionString="Data Source=$(Server);Initial Catalog=$(Catalog);User ID=$(User);Password=$(Password)" providerName="System.Data.SqlClient" />

<add key="$(Server)" value="xxxx" />
<add key="$(Catalog)" value="xxxx" />
<add key="$(User)" value="xxxx" />
<add key="$(Password)" value="xxxx" />

I added a custom directory in views folder and I wanna run my view, that is all.

  • First, I declared myCustom Route Option
  • Then, I need to connect my controller to view, how to do it ?


first one

second one :

I have a view file which conditionally calls one of four other view files depending on the selection of a drop down box. In one of these views I'm compiling a list of rules that I want to store in a string to persist. The second view is called from a switch statement as so -

case UITaskType.Validation:
        Html.RenderPartial("_ManageValidationTask", Model);     

When the user saves the page it uses an input type="submit" from the first view, so that the process is picked up on the post back as follows

<script type="text/javascript">
$(document).ready(function () {
    $("#Task_TaskTypeID").change(function () {
        if ($(this).val()) {

It's here that I want to call the other view with the list of rules to save them. I've created a function called buildRules() in the other view but have been unable to call it from this function.

I have a website that is CMS controlled and when I added a page today it was showing as my 404 page. So I went into my global.asax file and turned off friendly error pages so that I could see what was happening when I tried to get to the page. Once the page had finished indexing again, it showed up as originally expected. I then turned friendly errors back on and it continued to work.

Obviously amending my global.asax file fixed this error and I presume that's because it restarted my app pool but I don't understand why this would have stopped it from 404-ing. Can anyone explain?

I want the shopping cart working for every user who is registered.Also Cart Table goes with foreignKey UniqueUserId to Id[PK] of identity AspNetUSers table.Here is the code where I was stuck (ShoppingCart.cs) :

public partial class ShoppingCart
    ApplicationDbContext storeDB = new ApplicationDbContext();
    string ShoppingCartId { get; set; }
    public int AddToCart(Item item)
        var cartItem = storeDB.Carts.SingleOrDefault(
            c => c.CartId == ShoppingCartId
            && c.ItemId == item.ID );

        if (cartItem == null)
            cartItem = new Cart
                ItemId = item.ID,
                CartId = ShoppingCartId,
                UserUniqueId = 
                Count = 1,
                DateCreated = DateTime.Now
        return cartItem.Count;

I can't find out how to bind UserUniqueId with AspNetUser Identity Id in AddToCart class. Here is the model class of shopping cart (Cart.cs):

public class Cart
    public int ID { get; set; }
    public string CartId { get; set; }
    public string UserUniqueId { get; set; }
    public int ItemId { get; set; }
    public int Count { get; set; }
    public System.DateTime DateCreated { get; set; }
    public virtual Item Item { get; set; }


Here is the AddToCart controller :

    public ActionResult AddToCart(int id)

        var addedItem = storeDB.Items
            .Single(item => item.ID == id);

        var cart = ShoppingCart.GetCart(this.HttpContext);

        int count = cart.AddToCart(addedItem);

        var results = new ShoppingCartRemoveViewModel
            Message = Server.HtmlEncode(addedItem.Name) +
                " has been added to your shopping cart.",
            CartTotal = cart.GetTotal(),
            CartCount = cart.GetCount(),
            ItemCount = count,
            DeleteId = id
        return Json(results);

I am trying to get started with Microsoft Azure Web App. I have a simple Web API App that calls the Google Directions Web Service from a controller.

When I use this URL:

 http://maps.googleapis.com/maps/api/directions/json?origin=gosport uk&destination=fareham uk&mode=driving

I get my response back fine.However when I use this URL:

https://maps.googleapis.com/maps/api/directions/json?origin=gosport uk&destination=fareham uk&mode=driving&mode=driving&departure_time=" + secs.ToString()+ "&traffic_model=pessimistic&units=imperial&key=myKey

I get a 500 response code Internal Server Error.

I have tested both URL's in a console app and on localhost with no errors. It looks like the HTTPS is causing the error in Azure. Can you help me?