I don't know what's wrong with the code i've tried to search for possible reasons but haven't figured out yet what's the problem actually.Now the issue is that my web form contains a gridview in which i've place a footer row which will allow the user to add the data and that data gets added to the database and gets binded to the gridview after clicking on the insert link button,But the problem comes when i fill the data and when press link button insert it adds the data twice in gridview and in database too everytime.Below is my whole code which is performing CRUD operation on gridview:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication5.WebForm2" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Label ID="lblMessage" runat="server" ForeColor="Green" EnableViewState="false" />

        <asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
            AutoGenerateColumns="false" Width="100%" OnRowEditing="GridView1_RowEditing" OnRowCancelingEdit="GridView1_RowCancelingEdit"
            OnRowUpdating="GridView1_RowUpdating" DataKeyNames="AutoId" OnRowDeleting="GridView1_RowDeleting" AllowPaging="true"
            PageSize="10" OnPageIndexChanging="GridView1_PageIndexChanging" ShowFooter="True" OnRowCreated="GridView1_RowCreated" OnRowCommand="GridView1_RowCommand">

            <Columns>

                <asp:TemplateField HeaderText="Edit">

                    <ItemTemplate>

                        <asp:LinkButton ID="lnkEdit" runat="server" Text="Edit" CommandName="Edit" />

                    </ItemTemplate>

                    <EditItemTemplate>

                        <asp:LinkButton ID="lnkUpdate" runat="server" Text="Update" CommandName="Update" />

                        <asp:LinkButton ID="lnkCancel" runat="server" Text="Cancel" CommandName="Cancel" />

                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:LinkButton ID="lnkBtnInsert" runat="server"
                            CommandName="Insert">Insert</asp:LinkButton>
                    </FooterTemplate>

                </asp:TemplateField>

                <asp:BoundField HeaderText="AutoId" DataField="AutoId" ReadOnly="true" />

                <asp:TemplateField HeaderText="First Name">

                    <ItemTemplate>

                        <%# Eval("FirstNAme") %>
                    </ItemTemplate>
                    <EditItemTemplate>

                        <asp:TextBox ID="txtFirstName" runat="server" Text='<%# Eval("FirstName") %>' />

                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
                    </FooterTemplate>

                </asp:TemplateField>

                <asp:TemplateField HeaderText="Last Name">

                    <ItemTemplate>

                        <%# Eval("LastName") %>
                    </ItemTemplate>
                    <EditItemTemplate>

                        <asp:TextBox ID="txtLastName" runat="server" Text='<%# Eval("LastName") %>' />

                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtlname" runat="server"></asp:TextBox>
                    </FooterTemplate>

                </asp:TemplateField>

                <asp:TemplateField HeaderText="Age">

                    <ItemTemplate>

                        <%# Eval("Age") %>
                    </ItemTemplate>
                    <EditItemTemplate>

                        <asp:TextBox ID="txtAge" runat="server" Text='<%# Eval("Age") %>' Columns="3" />

                        <asp:RequiredFieldValidator ID="REw" runat="server" ControlToValidate="txtAge" Text="*" />

                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:TextBox ID="txtlage" runat="server"></asp:TextBox>
                    </FooterTemplate>

                </asp:TemplateField>

                <asp:TemplateField HeaderText="Is Active?">

                    <ItemTemplate>

                        <%# Eval("Active").ToString().Equals("True") ? "Yes" : "No" %>
                    </ItemTemplate>

                    <HeaderStyle HorizontalAlign="Left" />

                    <EditItemTemplate>

                        <asp:DropDownList ID="dropActive" runat="server" SelectedValue='<%# Eval("Active") %>'>

                            <asp:ListItem Text="Yes" Value="True" />

                            <asp:ListItem Text="No" Value="False" />

                        </asp:DropDownList>

                    </EditItemTemplate>
                    <FooterTemplate>
                        <asp:DropDownList ID="ddlactive" runat="server">
                            <asp:ListItem Text="Yes" Value="True" Selected="True"></asp:ListItem>
                            <asp:ListItem Text="No" Value="False"></asp:ListItem>
                        </asp:DropDownList>
                    </FooterTemplate>

                </asp:TemplateField>

                <asp:TemplateField HeaderText="Delete?">

                    <ItemTemplate>

                        <span onclick="return confirm('Are you sure to delete?')">

                            <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" ForeColor="Red" CommandName="Delete" />

                        </span>

                    </ItemTemplate>

                </asp:TemplateField>

            </Columns>

            <AlternatingRowStyle BackColor="White" />

            <EditRowStyle BackColor="#efefef" />

            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />

            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />

            <RowStyle BackColor="#EFF3FB" HorizontalAlign="Center" />

            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />

            <SortedAscendingCellStyle BackColor="#F5F7FB" />

            <SortedAscendingHeaderStyle BackColor="#6D95E1" />

            <SortedDescendingCellStyle BackColor="#E9EBEF" />

            <SortedDescendingHeaderStyle BackColor="#4870BE" />

        </asp:GridView>
    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

namespace WebApplication5
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        string _connStr = ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                PopulateData();
            }

        }

        protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)
        {
            GridView1.EditIndex = e.NewEditIndex;
            this.PopulateData();
        }

        protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            GridView1.EditIndex = -1;
            this.PopulateData();
        }

        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            var autoID = GridView1.DataKeys[e.RowIndex].Value;

            using (SqlConnection conn = new SqlConnection(_connStr))
            {

                string sql = "Delete from PersonalDetail" +

                " where AutoId = @AutoId";

                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {

                    cmd.Parameters.AddWithValue(
                    "@AutoId", autoID);

                    conn.Open();

                    cmd.ExecuteNonQuery();

                    conn.Close();
                }
            }

            lblMessage.Text =
            "Record has been deleted successfully !";

            lblMessage.ForeColor = System.Drawing.
            Color.Red;

            this.PopulateData();
        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GridView1.PageIndex = e.NewPageIndex;
            this.PopulateData();
        }

        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            var autoID = GridView1.DataKeys[e.RowIndex].Value;

            GridViewRow row = GridView1.Rows[e.RowIndex] as GridViewRow;

            TextBox tFirstName = row.FindControl("txtFirstName") as TextBox;

            TextBox tLastName = row.FindControl("txtLastName") as TextBox;

            TextBox tAge = row.FindControl("txtAge") as TextBox;

            DropDownList dropActive = row.FindControl("dropActive") as DropDownList;

            using (SqlConnection conn = new SqlConnection(_connStr))
            {

                string sql = "Update PersonalDetail set FirstName = @FirstName,LastName=@LastName, Age= @Age, Active = @Active" + " where AutoId = @AutoId";

                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {

                    cmd.Parameters.AddWithValue(
                    "@FirstName", tFirstName.Text.Trim());

                    cmd.Parameters.AddWithValue(
                    "@LastName", tLastName.Text.Trim());

                    cmd.Parameters.AddWithValue(
                    "@Age", tAge.Text.Trim());

                    cmd.Parameters.AddWithValue(
                    "@Active", dropActive.SelectedValue);

                    cmd.Parameters.AddWithValue(
                    "@AutoId", autoID);

                    conn.Open();

                    cmd.ExecuteNonQuery();

                    conn.Close();
                }
            }

            lblMessage.Text =
            "Record updated successfully !";

            GridView1.EditIndex = -1;

            this.PopulateData();
        }
        private void PopulateData()
        {

            DataTable table = new DataTable();

            using (SqlConnection conn = new SqlConnection(_connStr))
            {

                string sql = "Select * from PersonalDetail";

                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {

                    using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
                    {

                        ad.Fill(table);
                    }
                }
            }

            GridView1.DataSource = table;

            GridView1.DataBind();
        }

        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
        {

        }

        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Insert"))
            {
                TextBox name = (TextBox)GridView1.FooterRow.FindControl("TextBox1");
                TextBox lname = (TextBox)GridView1.FooterRow.FindControl("txtlname");
                TextBox age = (TextBox)GridView1.FooterRow.FindControl("txtlage");
                DropDownList isactive = (DropDownList)GridView1.FooterRow.FindControl("ddlactive");
                using(SqlConnection conn = new SqlConnection(_connStr))
                {
                    SqlCommand cmd = new SqlCommand("INSERT INTO PersonalDetail(FirstName,LastName,Age,Active) VALUES('" + name.Text + "','" + lname.Text + "','" + age.Text + "','" + isactive.SelectedItem.Value + "')",conn);
                    cmd.CommandType = CommandType.Text;
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    //int result = cmd.ExecuteNonQuery();
                    conn.Close();
                }
            }
            lblMessage.Text =
            "Record has been Added successfully !";
            this.PopulateData();
            
        }
    }

}

i want to upload two pic and one file and other data using asp.net with following c#.but it giving error of Uploadresumepic.SaveAs(path1);

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class resume_add : System.Web.UI.Page
{
    string strConnString = ConfigurationManager.ConnectionStrings["JOBConnectionString1"].ConnectionString;
    string f1;
    string f2;
    string f3;
    string path1;
    string path2;
    string path3;
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void submitresumebtn_Click(object sender, EventArgs e)
    {

        using (SqlConnection con = new SqlConnection(strConnString))
        {

            if (Uploadresumepic.PostedFile.ContentLength > 0)
            {
                f1 = Path.GetFileName(Uploadresumepic.FileName);
                path1 = Server.MapPath("profile_pic") + "/" + f1;
                Uploadresumepic.SaveAs(path1);
            }
            if (FileUploadresumefile.PostedFile.ContentLength > 0)
            {
                f2 = Path.GetFileName(FileUploadresumefile.FileName);
                path2 = Server.MapPath("resume_file") + "/" + f2;
                FileUploadresumefile.SaveAs(path2);
            }
            if (coverimage.PostedFile.ContentLength > 0)
            {
                f3 = Path.GetFileName(coverimage.FileName);
                path3 = Server.MapPath("cover_image") + "/" + f3;
                coverimage.SaveAs(path3);
            }
            using (SqlCommand com = new SqlCommand("Recruiter_detail"))
            {

                using (SqlDataAdapter sda = new SqlDataAdapter())
                {
                    com.CommandType = CommandType.StoredProcedure;
                    com.Connection = con;
                    com.Parameters.AddWithValue("@profile_pic", f1);
                    com.Parameters.AddWithValue("@name", TextName.Text.Trim());
                    com.Parameters.AddWithValue("@headline", TxtHedline.Text.Trim());
                    com.Parameters.AddWithValue("@short_description", textdescription.Text.Trim());
                    com.Parameters.AddWithValue("@location", TextBoxlocation.Text.Trim());
                    com.Parameters.AddWithValue("@website_address", TextBoxadress.Text.Trim());
                    com.Parameters.AddWithValue("@salary", TextBoxsalary.Text.Trim());
                    com.Parameters.AddWithValue("@phone_no", TxtBoxphoneno.Text.Trim());
                    com.Parameters.AddWithValue("@resume_file", f2);
                    com.Parameters.AddWithValue("@cover_image", f3);
                    com.Parameters.AddWithValue("@facebook_Url", FbURL.Text.Trim());
                    com.Parameters.AddWithValue("@Twitter_Url", TwitterUrl.Text.Trim());
                    com.Parameters.AddWithValue("@google_url", GoogleUrl.Text.Trim());
                    com.Parameters.AddWithValue("@youtube_url", YoutubeUrl.Text.Trim());
                    com.Parameters.AddWithValue("@age", TextBoxage.Text.Trim());
                    com.Connection = con;
                    con.Open();
                    com.ExecuteNonQuery();
                    con.Close();
                }

                Lblsubmit.Text = "Resume Created";
            }

        }
    }

The sql create procedure i am using is:

USE [JOB]
GO


SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


CREATE PROCEDURE [dbo].[Recruiter_detail]
    @profile_pic varchar(50),
    @name varchar(50),
    @headline nvarchar(50),
    @short_description nvarchar(50),
    @location nvarchar(50),
    @website_address nvarchar(50),
    @salary nvarchar(50),
    @phone_no nvarchar(50),
    @resume_file nvarchar(50),
    @cover_image nvarchar(50),
    @facebook_Url nvarchar(50),
    @Twitter_Url nvarchar(50),
    @google_url nvarchar(50),
    @youtube_url nvarchar(50)
AS
BEGIN
    SET NOCOUNT ON;
    IF EXISTS(SELECT Recruiter_id FROM Recruiter WHERE Username = '" + Session["name"] + "')
    BEGIN
        SELECT -1 
    END

    ELSE
    BEGIN
        INSERT INTO [Recruiter]
               ([profile_pic]
               ,[name]
               ,[headline]
               ,[short_description]
               ,[location]
               ,[website_address]
               ,[salary]
               ,[phone_no]
               ,[resume_file]
               ,[cover_image]
               ,[facebook_Url]
               ,[Twitter_Url]
               ,[google_url]
               ,[youtube_url]
               )
        VALUES
               (@profile_pic
               ,@name
               ,@headline
               ,@short_description
               ,@location
               ,@website_address
               ,@salary
               ,@phone_no
               ,@resume_file
               ,@cover_image
               ,@facebook_Url
               ,@Twitter_Url
               ,@google_url
               ,@youtube_url
               )


        SELECT SCOPE_IDENTITY() -- Recruiter_id            
     END
END


GO

the following tags in aspx code i am using

<div class="row">
                <div class="col-xs-12 col-sm-4">
                    <div class="form-group">

                        <asp:FileUpload ID="Uploadresumepic" type="file" class="dropify" data-default-file="assets/img/avatar.jpg" runat="server" />
                        <span class="help-block">Please choose a 4:6 profile picture.</span>
                    </div>
                </div>

                <div class="col-xs-12 col-sm-8">
                    <div class="form-group">
                        <asp:TextBox ID="TextName" type="text" class="form-control input-lg" placeholder="Name" runat="server"></asp:TextBox>
                    </div>

                    <div class="form-group">
                        <asp:TextBox ID="TxtHedline" type="text" class="form-control" placeholder="Headline (e.g. Front-end developer)" runat="server"></asp:TextBox>
                    </div>

                    <div class="form-group">
                        <asp:TextBox ID="textdescription" class="form-control" rows="3" placeholder="Short description about you" runat="server"></asp:TextBox>
                    </div>

                    <hr class="hr-lg">

                    <h6>Basic information</h6>
                    <div class="row">

                        <div class="form-group col-xs-12 col-sm-6">
                            <div class="input-group input-group-sm">
                                <span class="input-group-addon"><i class="fa fa-map-marker"></i></span>
                                <asp:TextBox ID="TextBoxlocation" type="text" class="form-control" placeholder="Location, e.g. Melon Park, CA" runat="server"></asp:TextBox>
                            </div>
                        </div>

                        <div class="form-group col-xs-12 col-sm-6">
                            <div class="input-group input-group-sm">
                                <span class="input-group-addon"><i class="fa fa-globe"></i></span>
                                <asp:TextBox ID="TextBoxadress" type="text" class="form-control" placeholder="Website address" runat="server"></asp:TextBox>
                            </div>
                        </div>

                        <div class="form-group col-xs-12 col-sm-6">
                            <div class="input-group input-group-sm">
                                <span class="input-group-addon"><i class="fa fa-usd"></i></span>
                                <asp:TextBox ID="TextBoxsalary" type="text" class="form-control" placeholder="Salary, e.g. 85" runat="server"></asp:TextBox>
                                <span class="input-group-addon">Per hour</span>
                            </div>
                        </div>

                        <div class="form-group col-xs-12 col-sm-6">
                            <div class="input-group input-group-sm">
                                <span class="input-group-addon"><i class="fa fa-birthday-cake"></i></span>
                                <asp:TextBox ID="TextBoxage" type="text" class="form-control" placeholder="Age" runat="server"></asp:TextBox>
                                <span class="input-group-addon">Years old</span>
                            </div>
                        </div>

                        <div class="form-group col-xs-12 col-sm-6">
                            <div class="input-group input-group-sm">
                                <span class="input-group-addon"><i class="fa fa-phone"></i></span>
                                <asp:TextBox ID="TxtBoxphoneno" type="text" class="form-control" placeholder="Phone number" runat="server"></asp:TextBox>
                            </div>
                        </div>

                        <div class="form-group col-xs-12 col-sm-6">
                            <div class="input-group input-group-sm">
                                <span class="input-group-addon"><i class="fa fa-envelope"></i></span>
                                <asp:TextBox ID="TextBoxaddress" type="text" class="form-control" placeholder="Email address" runat="server"></asp:TextBox>
                            </div>
                        </div>

                    </div>



                </div>
            </div>
<div class="button-group">
                <div class="action-buttons">

                    <div class="upload-button">
                        <button class="btn btn-block btn-gray">Choose a resume file</button>
                        <asp:FileUpload ID="FileUploadresumefile" type="file" runat="server" />
                    </div>

                    <div class="upload-button">
                        <button class="btn btn-block btn-primary">Choose a cover image</button>
                        <asp:FileUpload ID="coverimage" type="file" runat="server" />
                    </div>

                </div>
            </div>
<div class="row">
                <div class="col-xs-12 col-sm-6">
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="fa fa-facebook"></i></span>
                            <asp:TextBox ID="FbURL" type="text" class="form-control" placeholder="Profile URL" runat="server"></asp:TextBox>
                        </div>
                    </div>

                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="fa fa-google-plus"></i></span>
                            <asp:TextBox ID="GoogleUrl" type="text" class="form-control" placeholder="Profile URL" runat="server"></asp:TextBox>
                        </div>
                    </div>




                </div>

                <div class="col-xs-12 col-sm-6">
                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="fa fa-twitter"></i></span>
                            <asp:TextBox ID="TwitterUrl" type="text" class="form-control" placeholder="Profile URL" runat="server"></asp:TextBox>
                        </div>
                    </div>





                    <div class="form-group">
                        <div class="input-group">
                            <span class="input-group-addon"><i class="fa fa-youtube"></i></span>
                            <asp:TextBox ID="YoutubeUrl" type="text" class="form-control" placeholder="Profile URL" runat="server"></asp:TextBox>
                        </div>
                    </div>
                </div>
            </div>
<asp:Button ID="submitresumebtn" class="btn btn-success btn-xl btn-round" runat="server" Text="Submit your resume" OnClick="submitresumebtn_Click" />

On my phone, using LTE (not wifi), if I go to whatismyipaddress.com, it reports the IP address as 166.216.xxx.xxx. But if I go to whatismyip.com, it is reported as 107.77.xxxx.xxx. Why is that?

When I connect to my server with my phone (again LTE, not wifi), the server-side ASP.Net code attempts to retrieve the IP address via Request.UserHostAddress, and it is always 166.216.xxx.xxx. But how can I retrieve the 107.77.xxxx.xxx address instead? I've tried using Request.ServerVariables["HTTP_CLIENT_IP"] and Request.ServerVariables["HTTP_X_FORWARDED_FOR"] to no avail (both return null), and Request.ServerVariables["REMOTE_ADDR"] returns the same 166.216.xxx.xxx value as Request.UserHostAddress.

I've tried to limit the scope of my problem to the questions above, so if you can answer those sufficiently, I should (hopefully) be able to solve my issue. But in case you're wondering why this is a problem for me, read on.

I'm developing a phonegap application and on my production server (hosted in Azure) Request.UserHostAddress returns the 166.216.xxx.xxx IP address when I connect to it via the mobile browser (Safari) BUT returns the 107.77.xxxx.xxx IP address when I connect to it via my phonegap app.

I'm attempting to do so some very short-term, time-sensitive, identification of the connecting user's device when they access my server via the mobile browser (Safari), and then subsequently access it via the installed phonegap app, and the IP address figures into the algorithm, but because it's reported differently from the mobile browser vs the app it doesn't work properly.

At first I thought it was something to do with the how the phonegap app's network connectivity works (and it still might be) but because I'm able to get two different IP addresses reported from whatismyipaddress.com and whatismyip.com when accessing those sites via the mobile browser (Safari), I figure it has more to do with the technique used to retrieve the client IP address.

Any help would be greatly appreciated, Thanks.

this is similar to Enabling Authentication with SIgnalR against Azure Mobile Services and a Javascript client but with a twist. I have a Zumo-authenticated app that has SignalR that I would like to locally debug. For the client,

public App()
{
#if DEBUG            
  var client = new MobileServiceClient(debugUrl);
  client.AlternateLoginHost = new Uri(releaseUrl);
#else
  var client = new MobileServiceClient(mobileAppReleaseUrl);
#endif
  var hub = new HubConnection(client.MobileAppUri.AbsoluteUri);
..
}

to authenticate SignalR, I am using

conn.Headers["x-zumo-auth"] = _appService.CurrentUser.MobileServiceAuthenticationToken;

and server-side I use

public class ZumoUserIdProvider : IUserIdProvider
{
    public string GetUserId(IRequest request)
    {
        if (request == null)
        {
            throw new ArgumentNullException("request");
        }

        if (request.User != null && request.User.Identity != null)
        {
            var identity = (ClaimsIdentity)request.User.Identity;
            var identifier = identity.FindFirst(ClaimTypes.NameIdentifier);
            if (identifier != null)
            {
                return identifier.Value;
            }
        }

        return null;
    }
}

along with

GlobalHost.DependencyResolver.Register(typeof(IUserIdProvider), () => new ZumoUserIdProvider());

Amazingly, this actually works when published to Azure, though I'm a little bit worried about Web Sockets (maybe I need to stuff the token into the query string). The problem now is that when debugging in localhost, although I am able to authenticate (social login), I always get unauthenticated when I try to use SignalR on the localhost side. How can I make it work?

i have been working on a website for some time now and i have come across a problem that i don't know how to solve. I am attempting to bind data from the Boat model with the BoatTypes model to produce a dynamic dropdownlist/dropdownlistfor that will update the dropdownlist when the data entries to the BoatTypes model are added/removed.
The Boat model:

public class Boat
{
    RowingApp3_1Context db = new RowingApp3_1Context();
    [Key]
    public virtual int BoatId { get; set; }
    [Display(Name = "Boat Name")]
    [Required(ErrorMessage = "Boat must have a name")]
    public virtual string BoatName { get; set; }
    [Display(Name = "Type")]
    [Required(ErrorMessage = "Boat must have a type")]
    public virtual List<BoatTypes> BoatType { get; set; }
    [Required(ErrorMessage = "Boat must have a status")]
    public virtual string Status { get; set; }
    public virtual IEnumerable<BoatDates> Bookings { get; set; }
    public int BoatTypesId { get; set; }
}

The BoatTypes model:

public class BoatTypes
{
    public int BoatTypesId { get; set; }
    public string TypeName { get; set; }
}

I have attempted to implement the method used at the c-sharpcorner(http://www.c-sharpcorner.com/uploadfile/4d9083/binding-dropdownlist-in-mvc-in-various-ways-in-mvc-with-data/), but to no avail. I have already created all the delete, index, create and other views, as well as the controllers for each model. Any help is much appreciated!

I have set the title in my layout as:-

@ViewBag.Title | Web Clubbed

And My Index.html has Viewbag.Title as :-

@{
  ViewBag.Title = "Welcome to webclubbed web developement & online marketing"; 
}

Now My title in Index.cshtml shows like :- Welcome to webclubbed web developement & online marketing | Web Clubbed

But I want to remove "| Web Clubbed" from title in Index.cshtml only. How can I do that?

Please HELP!!

I have a 4.4.2 version android razor HD I cannot get my system ui app started again because I hit force stop. Please help me resolve this problem.

In my current application I'm generating a fairly lengthy table to display to the user. I've been seeing some serious performance issues with it, which I've tracked down to usage of @Html.DisplayFor, and I'm not entirely sure why.

Edit: I've replaced the code sample with a more concise and reproducible setup.

In order to isolate the issue, I have created a new asp.net core MVC project using all default settings in visual studio, with no authentication. I created a view model as such:

public class TestingViewModel
{
    public int Id { get; set; }
    public string TextValue1 { get; set; }
    public string TextValue2 { get; set; }
}

Then added a controller which fills the view model with data to pass to the view:

    public IActionResult TestThings()
    {
        var list = new List<TestingViewModel>();
        for(var i = 0; i < 1000; i++)
            list.Add(new TestingViewModel {Id = i, TextValue1 = "Test", TextValue2 = "Test2"});

        return View(list);
    }

The view is the bare minimum possible to display the data:

@model List<DisplayForTest.ViewModels.TestingViewModel>

@foreach (var item in Model)
{
    @Html.DisplayFor(m => item.Id)
    @Html.DisplayFor(m => item.TextValue1)
    @Html.DisplayFor(m => item.TextValue2)
}

When running this code, it takes over one second to run! The culprit is the DisplayFor. If I change the view as follows:

@model List<DisplayForTest.ViewModels.TestingViewModel>

@foreach (var item in Model)
{
    @item.Id
    @item.TextValue1
    @item.TextValue2
}

This renders in 13ms. It's clear DisplayFor is adding a huge amount of time to rendering... on my PC that's nearly 0.4ms per call. While that's not bad in isolation, it makes it a pretty bad choice for lists or other things.

Is DisplayFor really just that slow? Or am I using it incorrectly?

I have everything setup and the functions are already working and everything seems just fine. Just have one doubt and I dont know if it is even possible. I have a button that opens a modalpopupextender, and in there, I have a form, which has another button that activates a dropdownlist (which is the one where I grab all the information) and after the click on the button, it is supposed to fill all the form. The problem is, it closes the modalpopupextender, and although the function is completing, what I dont want is to have the window closed, I mean refresh the popup without closing it.

Here it is...

Class.aspx

<asp:Panel ID="panelEmail" Height="680px" Width="800px" runat="server" CssClass="modalPopUp">
    <h2>Contact by Email:</h2>
    <hr />
    <blockquote>
        <legend>Pick the template to use: </legend>
        <asp:dropdownlist id ="ddlTemplate" runat ="server" Height="23px" Width="436px">
              </asp:dropdownlist >  
        <asp:Button ID="Button1" runat="server" Text="Select" OnClick="Template_Changed" />   
        <legend>Email Recipient: </legend>
        <asp:TextBox ID ="emailT" runat="server" Width="356px" Height="24px" Visible="true" Text="prueba@prueba.com"></asp:TextBox>
        <legend>Email Subject: </legend>
        <asp:TextBox ID ="title" runat="server" Width="356px" Height="24px" Visible="true" ></asp:TextBox> 
        <asp:TextBox ID ="txtDetails" runat="server" Width="672px" Height="267px" Visible="true" ></asp:TextBox>
        <ajaxToolkit:HtmlEditorExtender ID="TextBox1_HtmlEditorExtender" runat="server" TargetControlID="txtDetails" 
            EnableSanitization="false" DisplaySourceTab="true" >
        </ajaxToolkit:HtmlEditorExtender><br />      
        <legend>If you want to save the template, name it: (Optional) </legend>
        <asp:TextBox ID ="nameTemplate" runat="server" Width="356px" Height="24px" Visible="true" ></asp:TextBox>
        <br /><br />
        <div align="center">
        <asp:Button ID="Button2" runat="server" Text="Send Mail" OnClick="SendMail"/> 
        <asp:Button ID="Button3" runat="server" Text="Save Template" OnClick="saveTemplate"/>
        <asp:Button ID="btnCancelEmail" runat="server" Text="Cancel"  CausesValidation="false" />
        </div>
    </blockquote>           
</asp:Panel>

<!-- Código añadido por Enrique Bravo -->
<ajaxToolkit:ModalPopupExtender ID="ModalPopupExtender4" runat="server"
    PopupControlID="panelEmail" 
    TargetControlID="lnkEmail"
    CancelControlID="btnCancelEmail"
    BackgroundCssClass="modalBackGround" 
    DropShadow="true" ></ajaxToolkit:ModalPopupExtender>

                        <tr id="trEmail">
                            <td>
                                <asp:Image ID="Image1" runat="server" ImageUrl ="Images/share.png" width="22px" height="22px" />
                            </td>
                            <td align="left" valign="middle">
                                  <asp:LinkButton ID="lnkEmail" runat="server" Text="Email Contact" ></asp:LinkButton> 
                            </td>
                        </tr>

Class.aspx.cs

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack){
loadlist();
         }
    }

    public void loadList()
    {
        if (!this.IsPostBack)
        {
            try
            {
                BO.Messages template = new BO.Messages();
                ddlTemplate.DataSource = template.GetAll();
                ddlTemplate.DataTextField = "Title";
                ddlTemplate.DataValueField = "Id";
                ddlTemplate.DataBind();
                ddlTemplate.SelectedIndexChanged += Template_Changed;
            }
            catch (Exception e)
            {
                e.ToString();
            }
        }
    }

    /// <summary>
    /// Select the correct Message if there has been one template selected
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void Template_Changed(object sender, EventArgs e)
    {

        int countryId = int.Parse(ddlTemplate.SelectedItem.Value);
        if (countryId > 0)
        {
            BO.Messages texto = new BO.Messages();
            txtDetails.Text = texto.GetByID(countryId).Body;
            title.Text = texto.GetByID(countryId).Subject;

        }
    }

I have this problem concerning asp DropDownList. My DropDownList contains many ListItem with different texts but some may have the same value.

Now whenever I select an item in the DropDownList and click a button to save, the selected Index changes to a different index. I realize that the new selected Index changed to usually have the same value as the index I selected in the first place.

            <asp:DropDownList ID="ddlNature_of_Business" runat="server" >
                <asp:ListItem Value="" Text="SELECT"></asp:ListItem>
                <asp:ListItem Value="3" Text="BDC / MFB"></asp:ListItem>
                <asp:ListItem Value="3" Text="Money Transmitter"></asp:ListItem>
                <asp:ListItem Value="3" Text="Money Transmitter"></asp:ListItem>
                <asp:ListItem Value="3" Text="Leather Goods Store"></asp:ListItem>
                <asp:ListItem Value="3" Text="Car Dealer"></asp:ListItem>
                <asp:ListItem Value="3" Text="Travel Agency"></asp:ListItem>
                <asp:ListItem Value="3" Text="Jewel & Gem Dealer"></asp:ListItem>
                <asp:ListItem Value="3" Text="Imports/Exports"></asp:ListItem>
                <asp:ListItem Value="3" Text="Cash Intensive Business-Restaurants"></asp:ListItem>
                <asp:ListItem Value="3" Text="Cash Intensive Business-Retail Stores"></asp:ListItem>
                <asp:ListItem Value="3" Text="Cash Intensive Business-Furnished apartments"></asp:ListItem>
                <asp:ListItem Value="3" Text="Cash Intensive Business-Hotels"></asp:ListItem>
                <asp:ListItem Value="3" Text="Cash Intensive Business-etc"></asp:ListItem>
                <asp:ListItem Value="3" Text="Govt Contractors"></asp:ListItem>
                <asp:ListItem Value="3" Text="Weapons & Arms Dealers"></asp:ListItem>
                <asp:ListItem Value="2" Text="Charity Organizations"></asp:ListItem>
                <asp:ListItem Value="2" Text="NGOs"></asp:ListItem>
                <asp:ListItem Value="2" Text="Professional Service Provider - Lawyer"></asp:ListItem>
                <asp:ListItem Value="2" Text="Professional Service Provider - Accountant"></asp:ListItem>
                <asp:ListItem Value="2" Text="Professional Service Provider - etc"></asp:ListItem>
                <asp:ListItem Value="1" Text="Manufacturing"></asp:ListItem>
                <asp:ListItem Value="1" Text="Construction"></asp:ListItem>
                <asp:ListItem Value="1" Text="Others"></asp:ListItem>

            </asp:DropDownList>

Whenever I select Car Dealer, it changes to BDC / MFB, NGOs changes to Charity Organizations while Construction changes to Manufacturing

From my observation, the selected index changes to to the first ListItem with the same value as the selected ListItem

I've tried using HTML <select></select> instead but it still behaves the same even on different browsers.

The only solution I could think of now is to remove the Value attribute from the ListItem and use only the Text attribute. Then I'll save all the DropDownList Items in a table and write a C# method that gets their values using the SelectedItem's Text. But then I have over 30 more of DropDownList like this one but with different group of ListItem.

Does anybody knows a better workaround?

i have one problem. When i tried to modify web.config using powershell in sharepoint 2010 web application. It reloads config from configuration db which was updated wrongly earlier.

Do you know how i can delete web.config from db not from physical path(wwwroot). Any powershell command which help me to delete web application config from db. I will create it again using powershell.

I have the following Template in my detailsview to edit a date:

<EditItemTemplate>
                        <asp:TextBox id="EndDate" class="datefield" text='<%# Bind("EndDate")%>' runat="server"/>
                    </EditItemTemplate>

And I'm changing over to the edit mode with a button with the following code:

protected void Edit_Assignment(object sender, EventArgs e) {

            if (_gvAssignments.CurrentMode != DetailsViewMode.Edit) {
                _gvAssignments.ChangeMode(DetailsViewMode.Edit);
            }


        }

I also have both a document ready and a onclientclick function to invoke the datepicker.

$(document).ready(function() {
            $("#tabs").tabs();
            $(".datefield").datepicker();
            $("#StartDate").datepicker();
            $("#EndDate").datepicker();
        });

        function updateDatepickFields() {
            alert("Button clicked");
            $(".datefield").datepicker();
            $("#StartDate").datepicker();
            $("#EndDate").datepicker();
        };
        $(".datefield").on("focus",function() {
            $(".datefield").datepicker();
        });

however it just does not seem to be attaching the datepicker no matter what code I use.

I have a WebApi2 application. The initial load of the site is loading static content for a SPA application. When my Global.asax.cs file looks like the following, then the cookie isn't added to the response(as seen in the developer tools in the browser):

using System.Web.Http;
using System.Web;
using System.Security.Claims;
using System.Linq;

namespace Application
{
    public class WebApiApplication : HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }

        protected void Application_PostAuthorizeRequest()
        {
            var claimsPrincipal = HttpContext.Current.User as ClaimsPrincipal;
            if (claimsPrincipal != null)
            {
                var cookie = new HttpCookie(".UIROLES", "admin");
                HttpContext.Current.Response.Cookies.Add(cookie);
            }
        }
    }
}

When I change it to have a condition looking for that cookie and redirecting back to the root page(which is what is loading anyway), then the cookie is showing up(as seen in the developer tools in the browser). Here is the updated Global.asax.cs with the redirect:

using System.Web.Http;
using System.Web;
using System.Security.Claims;
using System.Linq;

namespace Application
{
    public class WebApiApplication : HttpApplication
    {
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }

        protected void Application_PostAuthorizeRequest()
        {
            var claimsPrincipal = HttpContext.Current.User as ClaimsPrincipal;
            if (claimsPrincipal != null)
            {
                if (HttpContext.Current.Request.Cookies[".UIROLES"] == null)
                {
                    var cookie = new HttpCookie(".UIROLES", "admin");
                    HttpContext.Current.Response.Cookies.Add(cookie);    
                    HttpContext.Current.Response.Redirect("http://localhost/Application");
                }
            }
        }
    }
}

I have tried to read a number of articles on cookies and asp.net, but I can't figure out why the first version isn't working and the second one is. If my UI application requires another trip to the server, I can make it an ApiController call instead to get the data, but it would seem to me that the extra trip to the server shouldn't be necessary.

Why is this working the way it is? Is there anyway I can get the first set of code to work without the need for a redirect or an additional api call?

everyone. I've developed the website with asp.net 4.0 and deployed the in the IIS 7.5. I want to add some https for the certain web aspx page. For example, for the login, the site uses login.aspx. When the user browsing that page, I want to add the https for login.aspx. How can I do? Thanks.

sorry about my bad english, i'm learning Typescript and Angular, and i'm trying to upload a file into my database but the code in the server side and client is in Javascript and i dont know how to transform the code to Typescript, could you guys help me? This is the code:

app.controller('MyCtrl',function($scope){
    $scope.$watch('files.length',function(newVal,oldVal){
        console.log($scope.files);
    });
});

 app.controller('MyCtrl',function($scope){

    ...

    $scope.onSubmit = function(){
        var formData = new FormData();
        angular.forEach($scope.files,function(obj){
            formData.append('files[]', obj.lfFile);
        });
        $http.post('./upload', formData, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        }).then(function(result){                  
        },function(err){
        });
    };

    ...

});
var express = require('express');
var formidable = require('formidable');
var app = express();
app.use(express.static(__dirname + '/public'));

...

app.post('/upload',function(req,res){
    var form = new formidable.IncomingForm();
    form.uploadDir = __dirname +'/public/uploads';
    form.parse(req, function(err, fields, files) {
    });
    form.on ('fileBegin', function(name, file){
        file.path = form.uploadDir + "/" + file.name;
    });
    form.on ('end', function(){
        res.sendStatus(200);   
    });
});

...
var express = require('express');
var multer = require('multer');
var app = express();
app.use(express.static(__dirname + '/public'));

...

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, __dirname +'/public/uploads');
        //modify upload dest
    },
    filename: function (req, file, cb) {
        cb(null, file.originalname);
    }
});
var upload = multer({ "storage": storage });
var type = upload.array('files[]');

app.post('/upload',type,function(req,res){
    res.sendStatus(200);
});

...

This question already has an answer here:

In my logging page if i give correct username and password then it works good but if i give wrong username and password then it shows Object reference not set to an instance of an object I understood why it said this but could not get answer though i try many way. My LoginButton code is given bellow :

     protected void loginButton_Click(object sender, EventArgs e)
       {            
        Admin aAdmin = new Admin();
        aAdmin.AdminName = userNameTextBox.Text;
        aAdmin.AdminPassword = userPasswordTextBox.Text;
         //AdminManager is for show message
        AdminManager aAdminManager= new AdminManager();
         //Call function aAdminManager.GetAdmin(aAdmin)
        messageLabel.Text= aAdminManager.GetAdmin(aAdmin);
        Session["UserName"] = aAdmin.AdminName;
        Response.Redirect("Index.aspx");
      }

AdminManager.cs

public class AdminManager
{

    AdminGateway aAdminGateway=new AdminGateway();
    public string GetAdmin(Admin aAdmin)
    {
        // call function aAdminGateway.GetAdmin(aAdmin) for SQL Query
       int rowAffected= aAdminGateway.GetAdmin(aAdmin);
       if (rowAffected == 1)
        {

        }
        else
       {
           return "UserName or Password Wrong!";
       }
        return "";
    }
}

AdminGateway.cs

public int GetAdmin(Admin aAdmin)
    {
        Query = "SELECT * FROM Admin WHERE UserName='" + aAdmin.AdminName + "'AND Password='" + aAdmin.AdminPassword +
                "'";
        Command = new SqlCommand(Query, Connection);
        Connection.Open();
        int rowAffected = Convert.ToInt32(Command.ExecuteScalar().ToString());//this line give exception
        Reader.Close();
        Connection.Close();
        return rowAffected;
    }

I want after checking QUERY if any row doesn't affected then it back to AdminManager.cs and my message are in this code and return AdminLoggin.aspx.cs then show message that username and/or password error. How to solve this exception and show message for wrong username and password.

I cant see the dropdown list I created (click this link for image)

Here is my code in add.aspx.cs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

//ADO.NET
using System.Data;
using System.Data.SqlClient;
using System.IO;

public partial class Admin_Users_Add : System.Web.UI.Page
{
      SqlConnection con = new SqlConnection(kmb.GetConnection());
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GetCategoryTypes();
        }
    }
    /// <summary>
    /// Allows the user to display list of user types
    /// from the table Types to the dropdownlist control
    /// </summary>
    void GetCategoryTypes()
    {


            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandText = "SELECT CatID, Category FROM Categories";
            SqlDataReader dr = cmd.ExecuteReader();
            ddlCategoryTypes.DataSource = dr;
            ddlCategoryTypes.DataTextField = "Category";
            ddlCategoryTypes.DataValueField = "CatID";
            ddlCategoryTypes.DataBind();

            ddlCategoryTypes.Items.Insert(0, new ListItem("Select one...", ""));
            con.Close();

In database I created 2 tables:

Categories(CatID [PK], Category[FK])

CategoryTypes(Category [PK], Appetizers, Desserts, Beverages)

---- I want to see the "Appetizers, Desserts, Beverages" in the dropdown list which is from database, in my webpage

enter image description here is this possible to do dividing the series. Full of one series one side and another series is one side same as the image by using charts can anyone tell me please how to do this. Thank you

I am creating an online examination system and in admin panel i am creating the create exam event. I created a from for launch the exam. I want after click on launch button exam details should be submit in database which is easy but i also want the form created for launching the exam should be also replaced with form for adding question for that exam.

Anybody has idea...plzz help me

Im following this tutorial. I Create my WebApi and works Ok from the browser. But when try to add it as web reference tell me this error.

The document at the url http://localhost/WebApi/api/test was not recognized as a known document type. The error message from each known type may help you fix the problem: - Report from 'XML Schema' is 'Data at the root level is invalid. Line 1, position 1.'. - Report from 'DISCO Document' is 'Data

TestController

namespace WebApi.Controllers
{
    public class TestController : ApiController
    {
        public HttpResponseMessage Get()
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("GET: Test message")
            };
        }

        public HttpResponseMessage Post()
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("POST: Test message")
            };
        }

        public HttpResponseMessage Put()
        {
            return new HttpResponseMessage()
            {
                Content = new StringContent("PUT: Test message")
            };
        }
    }
}

Browser OK, but show error.

enter image description here