I have a view which contains two partial views. And in my controller I have a common action method for various http post methods here is the sample code:

 public ActionResult MyCommonMethode(modelclass object)
    {
 var BALObject = new BusinessLogic();
 -----------
 -----------
 return View("View", object);
    }

 [HttpPost, ActionName("MyCommonMethode"), Button(ButtonName = "searchbutton")]
    public ActionResult search(string searchstring)
    {
        ---------
         -------------
        return()
    }

 [HttpPost, ActionName("MyCommonMethode"), Button(ButtonName = "Save")]
    public ActionResult Edit(modelclass Object)
    {
        try
        {   -------------
             -----------
           -----------------
           return View("view", object);
        }
        catch (Exception e)
        {
             ----------------
            return RedirectToAction("error");
        }
    }

note that, the common method don't have any view, and it is not a http get method.

now if I want to use an ajax call/post rather than a form submit, like shown

  $("#button").click(function () {

    //Set inserted values
    var name = $("#textvalue").val();

    // Call Create action method
    $.post('/myController/search', {
        "searchstring": name,
    },
        function () {
            alert("data is posted successfully");
            window.location.reload(true);

        });
});  

so rather than loading the whole page I just want to refresh my partial view. what are all the things I have to take care. pls help.

Basically I want to display the version like "v1.1", where the version-number is in the ViewBag.

So I write v@ViewBag.Version in the markup.

But Razor will recognize this as an e-mail address.

I'm sure it will be blatantly obvious once I see it, but what is the escape to get what I want?

I've started with asp mvc 3, with c# and razor, then. I want to use forms with security for send petitions POST.

I want to with razor render some like that

<form action="/sass/" method="post">
     @using (Html.BeginForm()) {
        @Html.AntiForgeryToken()
        <div class="form-group">
            <label>Ingresa tu Nombre</label>
            <input class="form-control" name="nombre" />
        </div>
        <div class="form-group">
            <input type="submit" value="Enviar mi duda" class="btn btn-primary btn-sm" />
        </div>
     }

And in C# I dont know how to validate that csrf token, is valid. I work with C#, asp mvc3 and razor.

Please help me!

So my problem is that i want to hang an event to a checkbox in the view like this:

as you can see i ask for a notification in the changeFilter() method as soon as the checkbox changes. However when i create that method in the controller like this:

public EventHandler changeFilter()

    {
        ViewBag.test = "test";
        return null;(ignore the null please i know it's bad)
    }

it doesn't give me any results sadly nor does it ever reach that code. i want to reach that code so i can put filters on a list runtime that it refreshes and modifies the search result.

Does anybody have experience with this or anybody knows anything about it? i'd love some help

Thanks a lot in advance, Marijn

I want to have a "Back" button that returns a user back to a page with a grid/table on it, but I'm having some trouble. The point of the back button is to allow my user's grid settings to be persisted between viewing records. The link that the Back button points to depends on what URL the user comes from. The url is set in the controller method. When the Url looks like the following...

http://localhost:49933/OpenOrder

... there is very little problem getting the back button to work. However, when the URL looks like this...

http://localhost:49933/OpenOrder?grid-sort=&amp;grid-page=1&amp;grid-pageSize=1000&amp;grid-group=&amp;grid-filter=CustomerName~contains~&#39;TEST&#39;

... sometimes the "Back" button won't work at all. I'm using a Telerik Kendo MVC grid, and this is what happens to the URL when a user filters the page.

I have noticed that the following code in the view works consistently on all links when there is no form tag (e.g. @Html.BeginForm())...

View

<a href='@Url.Content(@ViewBag.PreviousReferrer)' style="display:none;">
    <input type="button" value="Back" />
</a>

But this doesn't work well with Views that do have the form tag. All I get is a Back button that I can click, but does absolutely nothing. It doesn't even show up in Fiddler.

Other things that I've tried include...

<input type="button" value="Back" onclick="@("window.location.href='" + @Url.Content(ViewBag.PreviousReferrer) + "'");" />
<input type="button" value="Back2" onclick="window.location.href = '@Url.Content(@ViewBag.PreviousReferrer)'" />
<input type="button" value="Back3" onclick="javascript:window.location=('@Url.Content(@ViewBag.PreviousReferrer)')" />

As stated previously, the ViewBag.PreviousReferrer property is set in the controller. Depending on whether a user is getting or posting, it will use either the Request.PreviousReferrer, or a session variable that I set. I won't include all my controller code since the rest of the pages work fine, but here's what it looks like when I set the ViewBag.PreviousReferrer in the gets and posts. At least one GET will come before any posts, so the session variable will always be set to something.

Controller

GET
string urlReferrer = Request.UrlReferrer == null ? string.Empty : Request.UrlReferrer.AbsoluteUri.ToUpper();
if (!string.IsNullOrEmpty(urlReferrer) && urlReferrer.Contains("OPENORDER"))
{
    ViewBag.PreviousReferrer = Request.UrlReferrer.AbsoluteUri;
    Session["OpenOrderPreviousReferrer"] = Request.UrlReferrer.AbsoluteUri;
}
else
{
    ViewBag.PreviousReferrer = "~/OpenOrder";
}


POST
ViewBag.PreviousReferrer = Session["OpenOrderPreviousReferrer"] ?? "~/OpenOrder";

Ideally, this is what I want: One style of markup to go to the link in the PreviousReferrer REGARDLESS of whether or not the button is inside or outside of a form tag.

I think the problem might have something to do with HTML escape sequences, but I don't know if that's the technical term for it.

I am writing an application that loads language texts from a database to enable internationalization, using keys in the viewmodels to find the correct text. I have modified a version of the MyLocalizationprovider from http://www.codeproject.com/Tips/514321/A-Simple-and-Effective-Way-to-Localize-ASP-Net-MVC, my modified code can be found here: https://gist.github.com/TheConfuser/5f4a64ebe13254e7d45b. The code goes thru the metadata-attributes and replaces the title(DisplayName), placeholder (Prompt), errormessage (ErrorMessage) and validation errormessage (ErrorMessage). I am fetching DisplayAttribute for ErrorMessage, Prompt and Name as well as ValidationAttribute for the ErrorMessage for validation between two fields, in this case passwords. I get the keys like this:

if (typeName.Equals("DisplayAttribute"))
{
    nameKey = ((DisplayAttribute) attr).Name;
    placeholderKey = ((DisplayAttribute) attr).Prompt;
...

And then I replace the keys with values from my database. My viewmodels looks like follows:

[Required(ErrorMessage = "changepassword_newpassword_error")]
[DataType(DataType.Password)]
[Display(Prompt = "changepassword_newpassword_placeholder", Name = "changepassword_newpassword_headline")]
[RegularExpression(@"^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{6,12}", ErrorMessage = "changepassword_newpassword_regexerror")]
public string NewPassword { get; set; }

This works fine for placeholders, titles, errormessages for the field and for the validation, however I have yet any idea of how to find the RegularExpression. I thought it would exist in the ValidationAttribute as its ErrorMessage does, but I cannot find anything there. See http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute(v=vs.110).aspx.

Where can I find the field for the regularexpression-string, does it even exist? Or should I try to write my own attribute (like Set RegularExpression Dynamically in Model), if so can anyone help me on the way?

I am using a Razor templating engine to render a very simple html page. The page has some various adverts that I am showing.

There is not code around the body closing tag but every once in while I get the following output

ody>
</b</html>

I have also seen the following

y>
</body</html>

Has anyone ever seen this behaviour before?

ps I am sorry this is a very flaky example, I am really confused and do not have any idea where to begin.

I have a multi line textbox on asp.net form and i am calling following javascript function on past event.

New lines are ignored if i paste any data.

I don't know if it is to do with javascript function. I can see '/n' in inner text but somehow it is not being rendered properly. "hello\nworld" is being rendered "hello world"

function handlepaste(textbox, e, label, len) {
    var savedcontent = textbox.innerHTML;
    if (e && e.clipboardData && e.clipboardData.getData) {// Webkit - get data from clipboard, put into editdiv, cleanup, then cancel event
        if (/text\/html/.test(e.clipboardData.types)) {
            textbox.innerHTML = e.clipboardData.getData('text/html');
        }
        else if (/text\/plain/.test(e.clipboardData.types)) {
            textbox.innerHTML = e.clipboardData.getData('text/plain');
        }
        else {
            textbox.innerHTML = "";
        }
        waitforpastedata(textbox, savedcontent);
        if (e.preventDefault) {
            e.stopPropagation();
            e.preventDefault();
        }
        return false;
    }
    else {// Everything else - empty editdiv and allow browser to paste content into it, then cleanup
        textbox.innerHTML = "";
        waitforpastedata(textbox, savedcontent, label, len);
        return true;
    }
}

function waitforpastedata(elem, savedcontent, label, len) {
    if (elem.childNodes && elem.childNodes.length > 0) {
        processpaste(elem, savedcontent, label, len);
    }
    else {
        that = {
            e: elem,
            s: savedcontent
        }
        that.callself = function () {
            waitforpastedata(that.e, that.s, label, len)
        }
        setTimeout(that.callself, 20);
    }
}

function processpaste(textbox, savedcontent, label, len) {
    pasteddata = textbox.innerHTML;

    if (savedcontent.length > 0) {
        textbox.innerHTML = savedcontent + pasteddata ;
    }

    if (pasteddata.length > len) {
        textbox.value = textbox.value.substring(0, len);
        document.getElementById(label).className = "red-text";
        document.getElementById(label).innerHTML = 'You are trying to type too much information ';
    }
    else {
        document.getElementById(label).className = "grey-text";
        document.getElementById(label).innerHTML = textbox.value.length.toString() + ' of ' + len + ' chars';
    }
}

I have 16 items named q1,q2,q3,...,q16 and txt_q1,txt_q2,...,txt_q16 And I need to check each one, so I have a for and inside I have the If like this:

For Cnt AS Integer = 1 To 16 Step 1
   If("q"&cnt = "") Then
      "txt_q"&cnt.Style.Add("color","blue")
      ....
      ..
   End If
End For 

The idea is check al items with a For to avoid the 16 Ifs, but I have a syntax error. What can I do?

the txt_q1,txt_q2... are IDs for asp:labels, and I have a radiobuttonList, so I get the radiobutton text and I set q1, q2, q3... to the corresponding radiobuttonlist. So I want to check if there is a radiobuttonlist that is not checked, if not I change the color to blue to the asp:label. So I want to avoid making 16 ifs for each radiobuttonlist and make it with a For, because the only thing that change in the variables is the number is the same "q" and the same "txt_q" so I want to add the number to "q" or "txt_q" to make it one variable called q1 or txt_q1 that already exist and that way acces to the txt_q1.Style.Add() and change the color of that label.

Thank You

I am adding a user to my aspnetusers database and that is working fine. Then I am also trying to link them to an existing role. That is when I get the error: "An asynchronous module or handler completed while an asynchronous operation was still pending."

Here is my method with the problem code:

private async void checkOldDB(string email, string password)
    {
        bool isValidUser = false;
        ReportsMvc.App_Code.BLL.FUN.cFunUser user = ReportsMvc.App_Code.DAL.FUN.cFunUserDB.getUser(email);
        if (user != null)
        {
            isValidUser = PasswordHash.PasswordHash.ValidatePassword(password, user.Password);
            if (!isValidUser)
            {
                isValidUser = PasswordHash.PasswordHash.ValidateHashes(password, user.Password);
            }
        }

        if (isValidUser)
        {
            var user2 = new ApplicationUser { UserName = email, Email = email };
            var result = await UserManager.CreateAsync(user2, password);

            if (result.Succeeded)
            {
                string role = user.Role;
                if (string.IsNullOrEmpty(role))
                {
                    role = "User";
                }
                UserManager.AddToRole(user2.Id, role);
                await SignInManager.SignInAsync(user2, isPersistent: false, rememberBrowser: false);                        
            }
        }
    }

The line starting with "await SignInManager" was working fine. Then when I added in that code to AddToRole, I started getting the above error. This identity/authentication stuff is all very new to me.

This question already has an answer here:

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 46:             @Html.LabelFor(model => model.passCode, htmlAttributes: new { @class =              "control-label col-md-2" })
Line 47:             <div class="col-md-10">
Line 48:                 @Html.ActionLink("Edit Password", "AdminEditSuperUserPassword", new { id=Model.id }) 
Line 49:             </div>
Line 50:         </div>

Stack Trace:

ASP._Page_Views_Admin_EditSuperUser_cshtml.Execute() in e:\Capstone\Capstone\Views\Admin\EditSuperUser.cshtml:48
System.Web.WebPages.WebPageBase.ExecutePageHierarchy() +271
System.Web.Mvc.WebViewPage.ExecutePageHierarchy() +120
System.Web.WebPages.StartPage.RunPage() +63
System.Web.WebPages.StartPage.ExecutePageHierarchy() +100
System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage) +131
System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance) +695
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +382
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +106
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +321
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9657896
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Controller:

    public ActionResult EditSuperUser(int id)
    {
        SuperUserVM superUser = SuperUserVM.Map(superUserLogic.GetSuperUserById(id));
        return View(superUser);
    }

    [HttpPost]
    public ActionResult EditSuperUser(SuperUserVM superUser)
    {
        superUserLogic.EditSuperUser(SuperUserVM.Map(superUser));
        Session["Edit"] = "true";
        return View();
    }

    public ActionResult AdminEditSuperUserPassword(int id)
    {
        SuperUserVM superUser = SuperUserVM.Map(superUserLogic.GetSuperUserById(id));
        return View(superUser);
    }

    [HttpPost]
    public ActionResult AdminEditSuperUserPassword(SuperUserVM superUser)
    {
        superUserLogic.EditSuperUserPassword(superUser.id, superUser.passCode, superUser.newPassword, superUser.confirmPassword);
        return RedirectToAction("EditSuperUser", new { id = superUser.id });
    }

I am editing a Super user with the id of 2, but the id isnt being passed back when i save the edited information.

My code here loops through a Customer and exports the result into a Excel document with multiple sheets, all depending on how many services/reports this customer has. What I want is to only get the column names and print them out into a gridview. Here is my full code where I run the customer and export everything to a excel file (which works fine). I seem totally lost here and I really do need some help.

  var custName = Convert.ToString(Request.QueryString["cusName"]);
        try
        {             
            DataSet dt = new DataSet();             
            SqlConnection connection = new SqlConnection("Data Source=AP;Initial Catalog=DB_inf;User Id=sa;Password=*****;App=EntityFramework");
            using (SqlCommand sqlCmd = new SqlCommand("info.dbo.SP_Accounting_GetAll_Services", connection))
            {
                sqlCmd.CommandType = CommandType.StoredProcedure;
                sqlCmd.Parameters.AddWithValue("@customerName", SqlDbType.NVarChar).Value = custName;
                using (SqlDataAdapter sqlDa = new SqlDataAdapter(sqlCmd))
                {
                    Session["TaskTable"] = dt;
                    sqlDa.Fill(dt);
                    if (dt.Tables.Count > 0)
                    {
                        MemoryStream ms = new MemoryStream();
                        int i = 1;
                        using (ExcelPackage package = new ExcelPackage(ms))
                        {
                            string filename = Server.MapPath("") + @"\Accounting_Templates\" + custName + ".xlsx";
                            FileInfo inputfile = new FileInfo(filename);
                            ExcelPackage summaryTemplate = new ExcelPackage(inputfile);
                            foreach (ExcelWorksheet sheet in summaryTemplate.Workbook.Worksheets)
                            {
                                package.Workbook.Worksheets.Add(sheet.Name, sheet);
                            }

                            foreach (DataTable table in dt.Tables)
                            {
                                var columns = new List<string>();


                                ExcelWorksheet worksheet = package.Workbook.Worksheets.ToList().Where(z => z.Name == string.Format("Report{0}", i)).FirstOrDefault();
                                if (worksheet != null)
                                {
                                    worksheet.Cells["A1"].LoadFromDataTable(table, true);
                                    worksheet.Cells.AutoFitColumns();
                                }
                                i++;
                            }
                            Response.Clear();
                            package.SaveAs(Response.OutputStream);
                            Response.AddHeader("content-disposition", "attachchment; filename=" + custName + ".xls");
                            Response.Charset = "";
                            Response.ContentType = "application/vnd.xls";
                            Response.End();
                        }
                   }
                }
            }
        }
        catch (Exception)
        {
            Page.ClientScript.RegisterStartupScript(GetType(), "msgbox", "alert('Something wen't wrong');", true);
        }

I've done this with PHP a while back, and now I want to do it with C#. I think I might be on the right track but something is going wrong along the way.

What I have is a "Create Order" page, which contains a basket of items that a user would like to purchase. On this page, they can search for products by name or sku, and grid view of results is displayed if they typed in something valid. They can then navigate to an add/update page where they can either add a new product to the basket or edit/update one already there. This takes them back to the basket page.

On the "Create Order" page, I am setting a session variable with the Cart ID based on whether a cart id is found in the url query string:

    protected void CreateSessionVariable()
    {
        string session = "";
        if (Request.QueryString["CartID"] != "" & Request.QueryString["CartID"] != null)
        {
            session = Request.QueryString["CartID"];
            Session["CartValue"] = session;
        }
        else
            Session["CartValue"] = "";
    }

I am then calling this is the Page_Load function:

        if (!Page.IsPostBack)
        {
            BindBasketGrid();
            //call function
            if (Session["CartValue"] != "" & Session["CartValue"] != null)
            {
                string CartCode = Request.QueryString["CartID"];
                CartIDLbl.Visible = true;
                CartIDLbl.Text += CartCode;
            }
            else
                CreateSessionVariable();
        }

In the add/update page's Page_Load, this is what I am calling (and it is called within !Page.IsPostBack:

                if (Session["CartValue"] != "" & Session["CartValue"] != null)
                {
                    string CartCode = Session["CartValue"].ToString();
                    CartIDLbl.Visible = true;
                    CartIDLbl.Text += CartCode;
                }

Things work for a little while--the Session variable is passed from the "Create Order" page to the Add/Update page successfully. But, when returning to the Create Order page, the session variable is no longer set.

Am I setting things up incorrectly?

I need to access a hidden fields value in code behind, normally this is easy but this variable is being set during jQuery's document.ready event and I need to access it when the page loads... so far I have tried Page_Load , Page_LoadComplete , Init and Prerender with no luck. Is this just an impossible task?

Thanks!

I have an asp.net MVC application that was exhibiting some strange authentication timeout behavior. We had the timeout on the forms authentication tag in the web.config set to two days.

    <forms loginUrl="~/Login/Index" timeout="2880" />

What we noticed though was the application was timing out around the 20 min mark. So, after researching the issue and trying various settings we decided to add code to the global.asax in the Applicatoni_AuthenticateRequest method that reads the ticket from the cookie, and updates the expiration .

Sub Application_AuthenticateRequest(sender As Object, e As EventArgs)
    Dim authCookie As HttpCookie = Context.Request.Cookies(FormsAuthentication.FormsCookieName)
    If (IsNothing(authCookie) OrElse authCookie.Value = "") Then
        Return
    End If

    Dim authTicket As FormsAuthenticationTicket
    Try
        authTicket = RefreshLoginCookie()
    Catch
        Return
    End Try

    'string[] roles = authTicket.UserData.Split(';');
    'if (Context.User != null) Context.User = new GenericPrincipal(Context.User.Identity, roles);

End Sub

Function RefreshLoginCookie() As FormsAuthenticationTicket

    Dim authCookie As HttpCookie = HttpContext.Current.Request.Cookies(FormsAuthentication.FormsCookieName)
    If (IsNothing(authCookie) OrElse authCookie.Value = "") Then
        Return Nothing
    End If

    Dim oldTicket As FormsAuthenticationTicket = FormsAuthentication.Decrypt(authCookie.Value)

    Dim expiryDate As Date = DateTime.Now.Add(FormsAuthentication.Timeout)
    HttpContext.Current.Response.Cookies.Remove(FormsAuthentication.FormsCookieName)

    Dim newTicket As FormsAuthenticationTicket = New FormsAuthenticationTicket(oldTicket.Version, oldTicket.Name, oldTicket.IssueDate, expiryDate, oldTicket.IsPersistent, oldTicket.UserData, oldTicket.CookiePath)
    authCookie.Value = FormsAuthentication.Encrypt(newTicket)
    authCookie.Expires = expiryDate

    HttpContext.Current.Response.Cookies.Add(authCookie)

    Return newTicket

End Function

Testing this in visual studio 2012 debugger everything worked beautifully, but once we deployed it to our IIS 7 environment the timeout issue returned.

To aid in my debugging I set the cookie expiration to be the same as the ticket's expiration so that I could easily tell what the ticket was being set to.

When the timeout occurs I see that the expiration should have occurred on 11/16, but that's not what's happening :

Here is the cookie information (at least the relevant information) Name Expiration .ASPXAUTH 11/16/2014, 9:00:47

putting logging in I see that the expiration update succeeds on the next request, but I still am getting sent to the login.

I'm stumped. I know it must be some setting in IIS 7 that is causing this because as I stated, it works fine in the debugger in visual studio (which is IIS 8 Express) so there must be something somewhere overriding this functionality.

I think it may be something specific to MVC though, because I'm using this same functionality on another site and am not seeing the same problem.

UPDATE

Forgot to mention, I'm also NOT seeing an authentication ticket timeout record in the event viewer.

I've to do some stuff when a changed occure in a TextBox in a GridView.. So I've:

$(function () {
    $('.mGrid').on('change', 'input[id*="txtValore"]', function () {
        alert('CHANGE!!');
        (...)
    });
});

The situation is:

<asp:UpdatePanel ID="FlussiPagamento" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        (...)
        <asp:Panel ID="pnlHome" runat="server">
            (...)
            <asp:GridView ID="gridPrincipale" CssClass="mGrid">
                (...)
                <asp:TemplateField> 
                    <ItemTemplate>
                        <asp:TextBox ID="txtValore" Text='<%# string.Format("{0:N}", Eval("Valore"))%>'
                        runat="server"  />
                    </ItemTemplate>
                </asp:TemplateField>
                (...)
            </asp:GridView>
            (...)
        </asp:Panel>
        <asp:Panel ID="pnlDettaglio" Visible="false" runat="server">
            (...)
            <asp:GridView ID="grid" CssClass="mGrid">
                (...)
                <asp:TemplateField> 
                    <ItemTemplate>
                        <asp:TextBox ID="txtValore" Width="90%" Text='<%# string.Format("{0:N}", Eval("Valore"))%>' runat="server"  />
                    </ItemTemplate>
                </asp:TemplateField>
                (...)
            </asp:GridView>
            (...)
        </asp:Panel>
        (...)
    </ContentTemplate>
</asp:UpdatePanel>

Rendered like this:

<div id="ctl00_MainContent_UpdatePanelID">
    (...)
    <div id="ctl00_MainContent_pnlHome">
        <table class="mGrid" id="ctl00_MainContent_gridPrincipale">
            (...)
            <tr>
                <td>
                    <input name="ctl00$MainContent$grdFlusso$ctl02$txtValore" type="text" value="1.920.442,73" id="ctl00_MainContent_gridPrincipale_ctl02_txtValore" />
                </td>
            </tr>
        </table>
    </div>
    (...)
    (This part when Visible=true)
    <div id="ctl00_MainContent_pnlDettaglio">
        (...)
        <table class="mGrid" id="ctl00_MainContent_grid">
            <tbody>
                (...)
                <tr>
                    (...)
                    <td>
                        <input name="ctl00$MainContent$grid$ctl03$txtValore" value="1.693,44" id="ctl00_MainContent_grid_ctl03_txtValore" onchange="test(this.id)" type="text">
                    </td>
                    <td>
                        <input name="ctl00$MainContent$grid$ctl03$txtRicalcolato" value="169,34" id="ctl00_MainContent_grid_ctl03_txtRicalcolato" onchange="test(this.id)" type="text">
                    </td>
                    (...)
                    <td>
                        <span id="ctl00_MainContent_grid_ctl03_lblDelta">-1.524,10</span>
                    </td>
                    (...)
                </tr>
                (...)
            </tbody>
        </table>
        (...)
    </div>
    (...)
</div>

In the first GridView I've also an ImageButton that does second griview databound and switch the panels visibility..In the second Panel I've another ImageButton, outside the GridView, that does the opposite.. I think both of it does a postback, because I can see the entire page is reloaded.. Now the behaviour is, when the first time the page is loaded if I change the first grid TextBox text I can see the alert. After I click the ImageButton and switch to second panel, the event is not fired when change text on second grid and if I come back to first panel, it don't work anymore not even with the first one.. What could be the problem?

In my AssemblyInfo.cs for a C# class library, I have the following:

[assembly: AssemblyTitle("Production")]

So when I compile, I get a dll project.dll and when I look at the windows file properties, it has the "Production" in the File Description field.

How do I also add the Date and Time to this File Description field??

When I set EnableOptimizations to true, certain css attributes seem to be missing. This is similar to other questions, but for them the entire css files are missing. For my case, it only seems to be certain attributes.

Specifically, the padding on container-fluid from bootstrap.css goes missing. Everything else works fine though.

 bundles.Add(new StyleBundle("~/Content/css").Include(
                  "~/Content/bootstrap.css",
                  "~/Content/bootstrap-theme.css",
                  "~/Content/site.css"));

I do not have the folder ~Content/css to cause the virtual directory issue as most other answers have stated.

I'm developing a Web Api 2.2 application with .NET Framework 4.5.1 and Asp.Net Identity 2.1.0.

I'm not sure what I'm doing, but I want to merge my database with ASP.NET Identity database and I have done this:

My own dbContext.

public class EFDbContext : IdentityDbContext, IUnitOfWork

My own User class.

public class User : 
   IdentityUser<long,
                IdentityUserLogin<long>,
                IdentityUserRole<long>,
                IdentityUserClaim<long>
               >

But when I do this:

UserManager<User> _userManager;

I get this error:

The type Data.Models.User cannot be used as parameter of type TUser. There isn't any explicit conversion from Data.Models.User to Microsoft.AspNet.Identity.IUser<string>.

I'm doing this because I want to have IdentityUser.Id as long instead of string.

How can I fix this error?

UPDATE

After updating UserManager with:

UserManager<User, long> _userManager;

I get the three errors here:

EFDbContext_ctx = context as EFDbContext;
_userManager = new UserManager<User, long>(new UserStore<User>(_ctx));

1. The best match of method overload for ' Microsoft.AspNet.Identity.UserManager <Data.Models.User,long>.UserManager (Microsoft.AspNet.Identity.IUserStore <Data.Models.User,long>)' has some invalid arguments-
2. The type 'Data.Models.User' cannot be used as parameter of type 'TUser' type or generic method 'Microsoft.AspNet.Identity.EntityFramework.UserStore <TUser>'. There is no conversion from implicit reference from 'Data.Models.User' to 'Microsoft.AspNet.Identity.EntityFramework.IdentityUser'.
3. Argument 1: cannot be converted from 'Microsoft.AspNet.Identity.EntityFramework.UserStore <Data.Models.User>' to 'Microsoft.AspNet.Identity.IUserStore <Data.Models.User,long>'

How can I fix this new error?

I've got a page with 3 GridViews.

<div id="Export" runat="server" class="headeropt noprint">

            <asp:LinkButton runat="server" ID="buttonexport" OnClick="buttonexport_Click" OnClientClick="Javascript:Noshow();" CssClass="btn btn-default">
                <asp:Image runat="server" ImageUrl="/images/Excel-16.gif" />
                <asp:Label runat="server" Text="Export" />
            </asp:LinkButton>
        </div>
<div class="col-md-12">
        <asp:GridView ID="grid1" runat="server" CellPadding="0" CssClass="table" CellSpacing="0" OnRowDataBound="grid1_RowDataBound" AutoGenerateColumns="false" GridLines="Vertical" BorderStyle="Solid" ShowFooter="true" OnRowEditing="grid1_RowEditing" datakeynames="grid1">
            <Columns>
                <asp:TemplateField HeaderText="Name">
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkname" runat="server" CausesValidation="false" CommandName="Edit" CommandArgument='<%# Eval("name") %>' Text='<%# Eval("name") %>'></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Company">
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Eval("company") %>'></asp:Label>
                    </ItemTemplate>
                    <ItemStyle CssClass="alinha-direita" />
                    <FooterStyle CssClass="alinha-direita" />
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

        <asp:GridView ID="grid2" runat="server" CellPadding="0" CssClass="table" CellSpacing="0" OnRowDataBound="grid2_RowDataBound" AutoGenerateColumns="false" GridLines="Vertical" BorderStyle="Solid" ShowFooter="true" OnRowEditing="grid2_RowEditing" datakeynames="grid2">
            <Columns>
                <asp:TemplateField HeaderText="Product Family">
                    <ItemTemplate>
                        <asp:LinkButton ID="lnkprdfamily" runat="server" CausesValidation="false" CommandName="Edit" CommandArgument='<%# Eval("prdfamily") %>' Text='<%# Eval("prdfamily") %>'></asp:LinkButton>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="">
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Eval("quantity") %>'></asp:Label>
                    </ItemTemplate>
                    <ItemStyle CssClass="alinha-direita" />
                    <FooterStyle CssClass="alinha-direita" />
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
        <asp:GridView ID="grid3" runat="server" CellPadding="0" CssClass="table" CellSpacing="0" OnRowDataBound="grid3_RowDataBound" AutoGenerateColumns="false" GridLines="Vertical" BorderStyle="Solid" ShowFooter="true" datakeynames="grid3">
            <Columns >
                <asp:TemplateField HeaderText="Product">
                    <ItemTemplate>
                        <asp:Label ID="Label2" runat="server" Text='<%# Eval("product") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Price">
                    <ItemTemplate>
                        <asp:Label ID="Label3" runat="server" Text='<%# Eval("price") %>'></asp:Label>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </div>

as you can see, the first grid links to the second, and the second to the third. What I want to know, is at any given time to get the grid I'm viewing at the moment.

Just edited adding the linkButton that exports the grid to excel. This is why I need the gridview that I'm currently on, so that the export command works at any time.

Here's the export code:

protected void buttonexport_Click(object sender, EventArgs c)
{
    Master.Page.Form.Attributes.Remove("onsubmit");
    CB.ChangeControlsToValue(grid1);
    string attachment = "attachment; filename=File.xls";
    //Response.ClearContent();
    Response.AddHeader("content-disposition", attachment);
    Response.ContentType = "application/ms-excel";
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    grid1.RenderControl(htw);
    Response.Write(sw.ToString());
    Response.End();
}

Thanks.

I created web service in visual studio 2010 three years back. I use this Web service in my winform project for performing some online functions. Now I want to create web service in visual studio 2013. Here I see web api instead of traditional web service. So my question is that what is the difference between traditional web service and Web api? And can I achieve the same thing in web api which I do in traditional web service?