I have a view model in my ASP.NET MVC application:

public class FiltersViewModel
{
    public IEnumerable<SelectListItem> AvailableFilters { get; set; } // fills a drop down menu

    public IList<TechnologyFilter> TechnologyFilters { get; set; }
    public IList<ContractTypeFilter> ContractTypeFilters { get; set; }

    public FiltersViewModel()
    {
        this.TechnologyFilters = new List<TechnologyFilter>();
        this.ContractTypeFilters = new List<ContractTypeFilter>();
    }
}

Then in my controller I pick up the selected value from the dropdown menu and create a specific filter object (Technology or ContractType filter) and then return the View, where I have the following code:

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
      @Html.AntiForgeryToken()

       @Html.DropDownListFor(m => m.SelectedFilterId, Model.AvailableFilters)

       if (Model.TechnologyFilters != null)
       {
           @for (int i = 0; i < Model.TechnologyFilters.Count; i++)
           {
             <div id="technologyFilter">
                @Html.HiddenFor(m => m.TechnologyFilters[i].Name)
                @Html.DisplayFor(m => mTechnologyFilters[i].Name)
             </div>
            }
       }  
}

If the HTML markup is done in this way and the viewmodel is posted back from the server, the viewmodel fills the TechnologyFilters list correctly. But when I extract the for loop in a partial view, the data stops being posted back correctly and my TechnologyFilters list is empty:

The same view, but this time calling partial view:

@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
     @Html.AntiForgeryToken()

     @Html.DropDownListFor(m => m.SelectedFilterId, Model.AvailableFilters)

     if (Model.TechnologyFilters != null)
     {
         Html.RenderPartial("_TechnologyFilters", Model.TechnologyFilters);
     }

_TechnologyFilters.cshtml partial view:

@model List<MVCFilters.Models.TechnologyFilter>

<div id="technologyFilters">
    @for (int i = 0; i < Model.Count; i++)
    {
        <div id="technologyFilter">
           @Html.HiddenFor(m => m[i].Name)
           @Html.DisplayFor(m => m[i].Name)
        </div>
    }
</div>

The HTML data in both cases is differently generated and I would like to have a way to have it constant (to be like the first picture).

Without using Partial View: enter image description here

Using Partial View: enter image description here

Thanks for any help provided!

I am trying to do a look up with Ajax and a dropdown list, The user enters a postcode in a text box, then clicks search. From here I want to populate a dropdown list, with the values coming from the database, The action is in a separate controller :-

public ActionResult Search(string Pcode)
{
return Json(new[] {
    new { value = '1', text = "text 1" },
    new { value = '2', text = "text 2" },
    new { value = '3', text = "text 3" }
});
}

My HTML:

  Pcode:- @Html.TextBox("GPPOST")
  GP Practice:
  @Html.EditorFor(model => model.Patient.GPSurgery)
  <br/>
   @Html.DropDownListFor(m =>m.Patient.GPSurgery     Enumerable.Empty<SelectListItem>(),"-- Select GP --")
                GP :  <input type="button" id="SearchPcode" value="Search">

And finally the Ajax:

        $(function () {
            $('#SearchPcode').click(function () {
                // get the new value
                var value = $(this).val();
                // and send it as AJAX request to the action
                $.ajax({
                    url: '/GP_Practices/Search',   //'<%= Url.Action("Search", "GP_Practices") %>',
                    type: 'POST',
                    data: { pcode: value },
                    success: function (result) {
                        // when the AJAX succeeds refresh the dropdown list with 
                        // The JSON values returned from the controller action
                        var GPNames = $('#Patient.GPSurgery');
                        GPNames.empty();
                        $.each(result, function(index, item) {
                            alert(item.text);
                        });

                        $.each(result, function (index, item) {
                            GPNames.append(
                                $('<option/>', {
                                    value: item.value,
                                    text: item.text
                                }));
                        });
                    }
                });
            });
        });

When I run the code I do get the Json results back, (which I can see in the alert box).

My 2 problems are:
1)I cannot seem to pass the value from the text box Html.TextBox("GPPOST")

2)The Dropdown list is not refreshing with the new values.

as practicing Ajax, I wrote a Ajax call that sends to a local asp.net Handler.ashx a Json with a username and password, and returns true if they are equal to "jhon" "123456", else false. I debugged the code, and I saw that the Handler.ashx receives the call, does the validation, and write to response, but the Ajax call not success.

this the Ajax call:

  $.ajax(
        {
            url: '/Handler.ashx',
            dataType: 'json',
            data: {
                name: document.getElementById("username").value,
                password: document.getElementById("password").value
            },
            success: function (json) {
                alert(json.isvalid);
            }
        });
        alert("failed");

and this is the server side:

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {
        Console.WriteLine("check");
        var name = context.Request["name"];
        var password = context.Request["password"];

        string response = IsValid(name, password) ? "true" : "false";
        context.Response.ContentType = "appliaction/text";
        context.Response.Write("{isvalid:'" + response + "'}");
    }

    private bool IsValid(string name, string password)
    {
        Console.WriteLine("isvalid");
        return (name == "jhon" && password == "123456");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}

thanks!

i have one checkbox (selectall) and checkboxlist.i bind some item in checkbox list. now i want to validate both checkbox and checkbox list ..like if all checkbox select then selectall should be selected and if any one is deselect then selectall should be deselect. also any one item should be select validate from submit. i try below code....

function CheckAll() {
    var intIndex = 0;
    var rowCount = document.getElementById('<%=chkBindComapany.ClientID %>').getElementsByTagName('input').length;
    for (i = 0; i < rowCount; i++) {
        if (document.getElementById('<%=cbAll.ClientID %>').checked == true) {
            if (document.getElementById('<%=chkBindComapany.ClientID %>' + '_' + i)) {
                if (document.getElementById('<%=chkBindComapany.ClientID %>' + '_' + i).disabled != true)
                    document.getElementById('<%=chkBindComapany.ClientID %>' + '_' + i).checked = true;
            }
        } else {
            if (document.getElementById('<%=chkBindComapany.ClientID %>' + '_' + i)) {
                if (document.getElementById('<%=chkBindComapany.ClientID %>' + '_' + i).disabled != true)
                    document.getElementById('<%=chkBindComapany.ClientID %>' + '_' + i).checked = false;
            }
        }
    }
}

function UnCheckAll() {
    var intIndex = 0;
    var flag = 0;

    var rowCount = document.getElementById('<%=chkBindComapany.ClientID %>').getElementsByTagName('input').length;
    for (i = 0; i < rowCount; i++) {

        if (document.getElementById('<%=chkBindComapany.ClientID %>' + '_' + i).checked == true) {
            flag = 1;

        } else {
            flag = 0;
            break;
        }

    }
    if (flag == 0) {
        document.getElementById('<%=cbAll.ClientID %>').checked = true;
        document.getElementById('lblmsg').innerHTML = "Please select atleast one item.";


    } else {
        document.getElementById('<%=cbAll.ClientID %>').checked = false;
        document.getElementById('lblmsg').innerHTML = "";

    }
}

i am currently working on my 1st ASP.NET-MVC project. My client asked me to expose web service that he need to use it in his android app. Now the problem is that i previously used web services in an ASP.NET projects. I don't have knowledge about WCF. So what should i prefer to expose web services in mvc. Should i have to go with API2 or is it OK if i use Web Services in MVC. any tutorial for this My friend suggest me to use API2 with MVC this it is easy to use as compare to WCF. thanks

In my flow say i am using an access token for getting my data. When my access token expires i get a 401 error i am using the refresh token to get a new access token.

Note : My access token and refresh token is stored in a cookie and i am updating the same after a 401 error.

My question how do i retry the same operation which i was in the middle of?

My Code (services.js):

 var refresh_token = "na";
function get_api_data(url, api_token) {
    var returnData = handleApiData(url, api_token, "GET");
    return returnData;
}

function post_api_data(url, api_token, post_data) {
    var returnData = handleApiData(url, api_token, "PUT", post_data);
    return returnData;

}

function handleApiData(url, access_token, type, post_data) {
    return $.ajax({
        url: url,
        type: type,
        data: post_data,
        error: failHandler,
        contentType: "application/json",
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", "Bearer " + access_token);
        }
    })
}

function handleData(data, textStatus, jqXHR) {
    return data;
}

function failHandler(jqXHR, textStatus, errorThrown) {
    switch (jqXHR.status) {
        case 401:
            var api = get_api_token();
            checkApiToken(api.refresh_token);
            break;
        default:
            alert(errorThrown);


    }
}
function checkApiToken(refresh_token) {
    if (refresh_token != "na") {
        $.post("/Account/Refresh/?refresh_token=" + refresh_token);
        //location.reload();
    }
}

My Code (notification.js):

 $(function () {
    var api = get_api_token();
    if (api != null)
        get_notification_data(api.access_token);

});

function get_notification_data(api_token) {

    var notifications = get_api_data(urls.notifications.list, api_token);
    if (notifications != undefined)
        notifications.success(function (data) {
            items = data.records;
            _.each(items, function (item) {
                item.Status = ko.observable(item.status);
                item.onClick = function () {
                    if (item.Status() === 'UNREAD') {
                        var post_data = { id: item.id };
                        post_api_data(urls.notifications.list, api_token, post_data).success(function (response, textStatus) {
                            if (response.success)
                                item.Status('READ');
                            $(location).attr("href", item.action_link);
                        });
                    }
                    else {
                        $(location).attr("href", item.action_link);
                    }

                }
            });
            var model = {
                items: ko.observableArray(items),
                onCancel: function (item) {
                }
            }
            ko.applyBindings(model, $("#notificationBar")[0]);
        })
}

Edit: My AccountController code that sets the new API cookie:

 [HttpPost]
    public ActionResult Refresh(string refresh_token)
    {
        string token_string = string.Empty;
        try
        {
            token_string = OAuthHelper.getTokenViaRefreshTokenFromAPIServer(refresh_token);
            if(token_string != null)
            Response.Cookies[Constants.Cookies.API].Value = token_string;
        }
        catch (Exception ex)
        {
            Log.Info(string.Format("AccountController.cs -Refresh Token Error ", ex.Message));

        }
       return RedirectToAction("Index","Home");
    }

Aspx Code:

 <asp:Repeater ID="rptProducts1" runat="server">
        <ItemTemplate>
            <div class="product_header">
                <asp:Label ID="prodLabels" runat="server" >
                    <p><h4><%#Eval("Name") %></h4></p>
                </asp:Label>
        <%--<p><%# Eval("Id") %>'><%#Eval("Name") %></p>--%>
    </div>

    <div class="left-col">
    <div class="img_product">

       <asp:Image ID="imgProduct" runat="server"  ImageUrl='<%# Eval("Picture") %>' Width="200px" Height="200px"/>

    </div>
        </div>

        </ItemTemplate>
        </asp:Repeater>

Code Behind:

 List<ProductModel> _prodObj = new List<ProductModel>();


                    _prodObj = response.Content.ReadAsAsync<List<ProductModel>>().Result;

                    _prodObj.Where(x => x.PictureId != 0).Select(v => v.Picture = "data:image/png;base64," + Convert.ToBase64String(v.PictureBinary));
                    var _prodname = _prodObj.Where(x=>x.Id!=0).Select(i => i.Name=""+i.Name);
                    try
                    {
                        rptProducts1.DataSource = _prodname;
                        rptProducts1.DataBind();
                    }
                    catch (Exception ex)
                    {

                        throw;
                   }

Hey guys another issue with fetching data from the database.I have taken a repeater and items.I want to display name and image of the product.The data is coming from the database but at the time of displaying it throws the above error.I am not getting the error and what steps to do to solve the problem. Please guide me with this error.

  1. I need always retrieved value form cache not database 2.But cache fetch data from database every 5 min automatically 3.asynchronous update cache
  2. it is possible .....always hit database process slow 5 I think retrieve value cache fast , pls tell one

I'm a beginner to asp.net. I am working on a project where i have to convert MVC into a class library.I don,t know how to write or register a controller in class library.

i am making an android app that can check Information which returned from ASP Web service (using Ksoap to interact with Web Service). I don't know why i can retrieve value with another Operation on WService but not with this, this is the value (json format) returned from my service:

<string>
{"Code":"nxbtrebk000001","Title":"VI DU","Description":"VI DU test","Author":"Tac Gia","Publisher":"NXB Tre","Price":99900,"Salt":"1"}
</string>

but when i get it from my Android app it's return a whole null json array like this:

{"Code":null,"Title":null,"Description":null,"Author":null,"Publisher":null,"Price":0,"Salt":null}

And this is my code i'm using to connect and get value from web service.

public final String SOAP_ACTION2 = "http://tempuri.org/GetBookItemByBarCode";
public final String OPERATION_NAME2 = "GetBookItemByBarCode";
public final String WSDL_PARAMETER_NAME2 = "Barcode";
public final String WSDL_TARGET_NAMESPACE2 = "http://tempuri.org/";
public final String SOAP_ADDRESS2 = "http://192.168.10.211/secudi";

public String CallSOAP_GetBookInfor(String paramBarcodeScannedData)
{
    // SOAP works on request response pair.

    SoapObject soapObjectRequest2 = new SoapObject(WSDL_TARGET_NAMESPACE2, OPERATION_NAME2);


    // Using setValue() method, set the value to the property.
    PropertyInfo bookItemBarcodeData2 = new PropertyInfo();
    bookItemBarcodeData2.setName(WSDL_PARAMETER_NAME2);
    bookItemBarcodeData2.setValue(paramBarcodeScannedData);
    bookItemBarcodeData2.setType(String.class);
    soapObjectRequest2.addProperty(bookItemBarcodeData2);

    // Create a serialized envelope which will be used to carry the parameters for SOAP body
    // and call the method through HttpTransportSE method.
    SoapSerializationEnvelope soapEnvelop2 = new SoapSerializationEnvelope(SoapEnvelope.VER11);
    soapEnvelop2.dotNet = true;
    soapEnvelop2.setOutputSoapObject(soapObjectRequest2);

    HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS2);
    Object soapResponse2 = null;

    try
    {
        httpTransport.call(SOAP_ACTION2, soapEnvelop2);

        soapResponse2 = soapEnvelop2.getResponse();
    }
    catch (Exception ex)
    {
        //soapResponse = ex.toString();
        ex.printStackTrace();
    }
    return  soapResponse2.toString();
    //return (String)soapResponse;

}

This is my Code Snippet which i using in my Activity to show the value in array.

      soapResponseBookItem = secuBookSOAPWS.CallSOAP_GetBookInfor(bBarcodeScannedData);
      JSONObject bookItemJSON;
      bookItemJSON = new JSONObject(soapResponseBookItem);

      TextView BookName = (TextView) findViewById(R.id.Book_Title);
      BookName.setText("Book Title: " + bookItemJSON.getString("Title"));

So you guys please help me to fix this, i'm mad with this. i was searhed whole google and stackoverflow but no method work with this.

I have two websites hosted on the same server via IIS. The two websites thus have the same IP address and use the different ports. And this is how we differentiate the two.

We are in the process of DNS mapping the two URLs, but the team that handles this, says that it cannot incorporate the port number in the urls.

Is there way from IIS to identify the particular website from the URL itself and direct it to the same?

I have an application that consists of a web application, and mutliple windows services, only one windows service is installed depending on what version of the backend sofware is used.

Currently, Data is saved by the web app in a database, then the relevant service is installed and this picks up the data and posts it in to the backend system that is installed.

I want to change this to use WCF services so the resulting data is returned directly to the web app.

I have not used WCF services before but Im assuming I can do something like this.

WebApp.Objects.Dll - contains Database objects, eg PurchaseOrder object

WebApp.Service.Contracts.dll - here I can describe the service methods, this will reference the WebApp.Objects.dll so I can take a PurchaseOrder object as a parameter

WebApp.Service.2011.dll - This will be the actual service for the 2011 version of the backend system, this will reference the WebApp.Service.Contracts dll

WebApp.Service.2012.dll - This will be the actual service for the 2012 version of the backend system, this will reference the WebApp.Service.Contracts dll

So, my question is, does the web app need to know the specifics about what backend WCF service is used? I just want to call a service with the specified Interface and not care about how its implemented or what it does internally, but just to return the purchase order that was created in the backend system (whether it return an interface or a concrete class)

Will i be able to create a service client without needing to know whether its the 2011, or 2012 WCF service being used?

My Windows service is in the same solution as a MVC project.

The MVC project uses a reference to SignalR Client which requires Newtonsoft.Json v6 +

the Windows service uses System.Net.Http.Formatting, which requires Newtonsoft.Json version 4.5.0.0.

I assumed this would not be a problem, as I could just use a binding redirect in my App.Config, however I get an error of

An unhandled exception of type 'System.IO.FileLoadException' occurred in System.Net.Http.Formatting.dll

Additional information: Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

my app.config has the following:

<dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
</dependentAssembly>

I added that myself, and it does not work, I have also tried uninstalling and re-installing Json.Net with the nuget package manager, to no avail

I keep getting the following parse error:

Server Error in '/' Application. Parser Error Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.

Parser Error Message: Only Content controls are allowed directly in a content page that contains Content controls.

Source Error:

Line 1: ate

Source File: /admin/JobCategories.aspx Line: 1

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34248

Problem is, the file in question doesn't have that string ("ate") anywhere in it. I did a search in visual studio for it, and found one file containing it.

Strangely enough, the file was shown as JobCategories(1).aspx. I opened it, and tru enough the string was appended to the start of the file. I deleted it, but the error persists, and now when I search for the string in VS I find no results. Tried restarting IIS, rebuilding the website in VS, and restoring an older version of the file from backup that used to work, but I still get the same error.

Only thing done on the file since the last backup was updating a string in the HTML, nothing to do with the code, and nothing near the beginning of the file.

Any ideas? Thanks.

How to track bounced emails and how to track mail is delivered?,

Here the following code i have used.

try
{
  Configuration configurationFile = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~/web.config");
                System.Net.Configuration.MailSettingsSectionGroup mailSettings = configurationFile.GetSectionGroup("system.net/mailSettings") as System.Net.Configuration.MailSettingsSectionGroup;


                string from = string.Empty;
                if (mailSettings != null)
                {
                    from = mailSettings.Smtp.From;
                }
                string myString="<html><head>test email tracking </head><body><p>this is test mail for email tracking</p></body></html>";

                string toAddress = "mohanj@icore.net.in";

                myString = myString.Replace("<body>", "<body><IMG height=1 src='http://icoremail.icore.net.in/testresponse.aspx?emailsent=" + toAddress + "' width=1></IMG>");



                using (MailMessage message = new MailMessage(

             //  from, "mohanj.icore@gmail.com",

             from, "mohanj@icore.net.in",
        "A report for you!", myString))
                {
                    message.IsBodyHtml = true;

                    SmtpClient smtp = new SmtpClient();

                    smtp.Send(message);
                    lblMessage.Text = " Mail Sent successfully! ";

                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.Message);
            }
        }

Can I acheive this using "DeliveryNotificationOptions" in asp.net

Thanks a lot. The Correct answer would be appreciated.

I have an ASP.NET 4 web-service.
It has an ImportModule action in a ModuleController controller.

That's how it works:

  1. The user uploads a module as a CSV-file.
  2. This file is being read using HttpPostedFileBase.InputStream and custom CSV-reading class.
  3. This file is being transformed to a C# object according to some rules and validations. If a file is valid, then it transforms to C# object, stores in a Cache with unique GUID name and a user is redirected to CompleteImportModule action.
  4. User checks if data is correct and he confirms uploading.

Long story short, there is a code which tells you more:
ImportModule action.

public ActionResult ImportModule(HttpPostedFileBase file)
{
    if (!ModelState.IsValid) 
    {
        return RedirectToAction("Index");
    }

    ModuleQuestion[] questions;
    ModuleInfo moduleInfo;
    string uploadId = Guid.NewGuid().ToString();

    // It is my custom CSV-reader and it works. Values are assigned
    FormDataCsvReader csvReader = new FormDataCsvReader(file.InputStream);
    if (!csvReader.Process(out questions, out moduleInfo))
    {
        // File is invalid
        return RedirectToAction("Index");
    }

    ViewBag.UploadId = uploadId;
    ViewBag.ModuleInfo = moduleInfo;
    ViewBag.Questions = questions;

    HttpContext.Cache.Add("UploadModule_" + uploadId,
        new Tuple<ModuleInfo, ModuleQuestion[]>(moduleInfo, questions),
        null,
        Cache.NoAbsoluteExpiration,
        TimeSpan.FromMinutes(30),
        CacheItemPriority.NotRemovable,
        (k, v, r) => 
        {
            LoggingFactory.GetLogger().Debug("Removed from cache: {0}. Reason: {1}", k, r);
        });     

    return View();   
}

In View ImportModule:

// Output data from ViewBag.ModuleInfo and ViewBag.Questions

<form method="POST" action="@Url.Action("CompleteImportModule")">
    <input type="hidden" name="uploadId" value="@ViewBag.UploadId"/>
    <input type="submit" value="Send">
</form>

CompleteImportModule action:

[HttpPost]
public ActionResult CompleteImportModule(string uploadId)
{
    var item = HttpContext.Cache["UploadModule_" + uploadId];
    if (item == null) RedirectToAction("Index");
    // upload module 
    HttpContext.Cache.Remove("UploadModule_" + uploadId);
    return RedirectToAction("Index");
}

However, I met some problems. I cannot upload the module because the value is removed from a Cache right after being inserted. It is stored only for a second:

DEBUG 2015-06-22 15:00:18,696 thread 85: Added to cache:
UploadModule_c843077d-21d0-4e9f-9e5e-3df82da4bac8

DEBUG 2015-06-22 15:00:19,935 thread 48: Removed from cache:
UploadModule_c843077d-21d0-4e9f-9e5e-3df82da4bac8. Reason: Removed

The reason is "Removed" meaning that it is not expired and IIS hasn't removed it due to optimization but it looks like I removed is myself. I am pretty sure that I am even not accessing this cache record before CompleteImportModule.

I have tried putting new StackTrace().ToString() in a CacheItemRemovedCallback. That's it, if it can help somehow:

at CPMAdministrator.Controllers.ModulesReferenceController.<ImportModule>b__9(String key, Object value, CacheItemRemovedReason reason)
   at System.Web.Caching.CacheEntry.CallCacheItemRemovedCallback(CacheItemRemovedCallback callback, CacheItemRemovedReason reason)
   at System.Web.Caching.CacheEntry.Close(CacheItemRemovedReason reason)
   at System.Web.Caching.CacheSingle.UpdateCache(CacheKey cacheKey, CacheEntry newEntry, Boolean replace, CacheItemRemovedReason removedReason, Object& valueOld)
   at System.Web.Caching.CacheSingle.Dispose(Boolean disposing)
   at System.Web.Caching.CacheMultiple.Dispose(Boolean disposing)
   at System.Web.HttpRuntime.Dispose()
   at System.Web.HttpRuntime.ReleaseResourcesAndUnloadAppDomain(Object state)
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
   at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
   at System.Threading.ThreadPoolWorkQueue.Dispatch()

Why is it happening? Is it sort of IIS pool recycling? How can I ensure that the file is not being removed? Or how can I effictively store this data another way?

I am developing a Online Evaluation Portal in Microsoft Visual Studio 2013 using C# and ASP.NET . I have kept a timer which starts once the page is loaded. For timer I used AJAX Timer. User should have 2 options - Submit test or Auto Submit once time is over. But I am not able to auto submit the page. I tried using Javascript in the code behind file but it doesn't work. The code for timer and auto submission is as follows :

protected void Timer1_Tick(object sender, EventArgs e) { if (0 > DateTime.Compare(DateTime.Now, DateTime.Parse(Session["timeout"].ToString()))) { int hrs = (((Int32)DateTime.Parse(Session["timeout"].ToString()).Subtract(DateTime.Now).TotalMinutes)) / 60; int mins = (((Int32)DateTime.Parse(Session["timeout"].ToString()).Subtract(DateTime.Now).TotalMinutes)) % 60; int seconds = (((Int32)DateTime.Parse(Session["timeout"].ToString()).Subtract(DateTime.Now).TotalSeconds)) % 60;

            lblTimer.Text = "Time left is " + hrs.ToString() + " : " + mins.ToString() + " : " + seconds.ToString();

            if (hrs == 0 && mins == 0 && seconds == 0)
            {
                string submit = "function Submit(){ alert('Test Over');document.forms[0].submit();}";
                ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "submit", submit, true);                          //This function is never called. I tried debugging it says dr1 not found, Whereas I never used dr1
                lblTimer.Text = "Time over";                   
            }
        }

I'm trying to get the current logged in usersID in my jquery function

var userID = @User.Identity.GetUserId();

Many answers on this page say that I have to do something like \"@User.Identity.GetUserId()\" But it dont seem to work, can someone tell me how to fix it.

Its for my ajax post.

$.ajax({
        url: '/video/check',
        type: 'POST',
        data: {
            userid: userID,
            streamid: defaultContext
        },
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            alert(data.success);
        },
        error: function () {
            alert("error");
        }
    });

Goal:
If the radio button ".... date(s)" is selected then the dropdownlist for start and end date will be NOT disabled.

Problem:
When you have selected and checked the radio button ".... date(s)" and then you press the search button. The radio button ".... date(s)" is checked but the dropdownlist for start and end date are disabled.

How to enable to make the dropdownlist to be active if ".... date(s)" is checked after you have pressed the search or submit button?

Information:
*If radio button is checked for "All ... only", the dropdownlist for start and end date shall be disabled.

*I'm using boostrap, jquery. asp.net mvc enter image description here CSHTML:

                Search for  &nbsp;&nbsp;&nbsp;

                @Html.RadioButtonFor(x => x.SelectionOfInputRadio, "all", new { id = "test", @class = "positionRadio test-or-dates", @checked = "checked" })
                <label for="all" class="labelPositionForRadio">All ... only</label>

                @Html.RadioButtonFor(x => x.SelectionOfInputRadio, "dates", new { id = "dates", @class = "positionRadio test-or-dates" })
                <label for="dates" class="labelPositionForRadio">date(s)</label>


@{
    DateTime myDate = DateTime.Today;

    List<SelectListItem> myListSelectListItem_YearStartDate = new List<SelectListItem>();

    for (int i = 0; i < 10; i++)
    {
        myListSelectListItem_YearStartDate.Add(new SelectListItem { Text = (myDate.Year - i).ToString(), Value = (myDate.Year - i).ToString(), Selected = DateTime.Today.Year == (myDate.Year - i) ? true : false });
    }
}


@Html.DropDownList("YearStartDate", myListSelectListItem_YearStartDate, new { @class = "date-selector", @disabled = "disabled" })

@Html.DropDownList("YearEndDate", myListSelectListItem_YearStartDate, new { @class = "date-selector", @disabled = "disabled" })



@{
    List<SelectListItem> mySelectListItem_month = new List<SelectListItem>();

    mySelectListItem_month.Add(new SelectListItem { Text = "January", Value = "01", Selected = DateTime.Today.Month == 1 ? true : false });
    mySelectListItem_month.Add(new SelectListItem { Text = "February", Value = "02", Selected = DateTime.Today.Month == 2 ? true : false });
    mySelectListItem_month.Add(new SelectListItem { Text = "March", Value = "03", Selected = DateTime.Today.Month == 3 ? true : false });
    mySelectListItem_month.Add(new SelectListItem { Text = "April", Value = "04", Selected = DateTime.Today.Month == 4 ? true : false });
    mySelectListItem_month.Add(new SelectListItem { Text = "May", Value = "05", Selected = DateTime.Today.Month == 5 ? true : false });
    mySelectListItem_month.Add(new SelectListItem { Text = "June", Value = "06", Selected = DateTime.Today.Month == 6 ? true : false });
    mySelectListItem_month.Add(new SelectListItem { Text = "July", Value = "07", Selected = DateTime.Today.Month == 7 ? true : false });
    mySelectListItem_month.Add(new SelectListItem { Text = "August", Value = "08", Selected = DateTime.Today.Month == 8 ? true : false });
    mySelectListItem_month.Add(new SelectListItem { Text = "September", Value = "09", Selected = DateTime.Today.Month == 9 ? true : false });
    mySelectListItem_month.Add(new SelectListItem { Text = "October", Value = "10", Selected = DateTime.Today.Month == 10 ? true : false });
    mySelectListItem_month.Add(new SelectListItem { Text = "November", Value = "11", Selected = DateTime.Today.Month == 11 ? true : false });
    mySelectListItem_month.Add(new SelectListItem { Text = "December", Value = "12", Selected = DateTime.Today.Month == 12 ? true : false });           
}


@Html.DropDownList("MonthStartDate", mySelectListItem_month, new { @class = "date-selector", @disabled = "disabled" })

@Html.DropDownList("MonthEndDate", mySelectListItem_month, new { @class = "date-selector", @disabled = "disabled" })


@{
    List<SelectListItem> myListSelectListItem_startdate = new List<SelectListItem>();

    for (int i = 1; i <= 31; i++)
    {
        SelectListItem mySelectListItem_startdate = new SelectListItem();
        mySelectListItem_startdate.Text = i.ToString();
        mySelectListItem_startdate.Value = i.ToString();
        mySelectListItem_startdate.Selected = i.ToString() == DateTime.Today.Day.ToString() ? true : false;

        myListSelectListItem_startdate.Add(mySelectListItem_startdate);
    }
}


@Html.DropDownList("DayStartDate", myListSelectListItem_startdate, new { @class = "date-selector", @disabled = "disabled" })

@Html.DropDownList("DayEndDate", myListSelectListItem_startdate, new { @class = "date-selector", @disabled = "disabled" })


<input type="submit" value="Search" />

Javascript

<script>

    $('.test-or-dates').on('click', function () {
        var _this = $(this);

        var dateSelectors = $('.date-selector');

        if (_this.attr('id') == 'all') {
            dateSelectors.attr('disabled', true);

        }
        else {
            dateSelectors.attr('disabled', false);
        }
    });
</script>

I fairly new to Ajax post, and I wonder if someone could help me with why i keep getting the error message.

VideoController

[HttpPost]
    public ActionResult Check(string userid, string streamid)
    {
        return Json(new { success = true });
    }

The reason why the httppost is fairly empty yet is just to test if it works before i start writing the code.

Jquery

var userID = '@User.Identity.GetUserId()';
var defaultContext = window.location.hash === "" ? XSockets.Utils.guid() : window.location.hash.substr(1);
    //alert(defaultContext);

    $.ajax({
        url: '/video/check',
        type: 'POST',
        dataType: 'json',
        data: JSON.stringify({
            userid: userID,
            streamid: defaultContext
        }),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            alert(data.success);
        },
        error: function (error) {
            alert(error.status);
        }
    });

I keep getting throw into my error: function and if I debug I never hit the [httpPost] Method

Can someone help

Update

I get a 404 in the alert.

RouteConfig

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

I'm trying to learn Claims for MVC 5 OWIN login. I try'ed to keep it as simple as possible. I started with the MVC template and inserted my claims code (see below). I get an error when I use the @Html.AntiForgeryToken() helper in the View.

Error:

A claim of type 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' or  
'http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovid    
er' was not present on the provided ClaimsIdentity. 

To enable anti-forgery token support with claims-based authentication, please verify that 
the configured claims provider is providing both of these claims on the ClaimsIdentity 
instances it generates. If the configured claims provider instead uses a different claim 
type as a unique identifier, it can be configured by setting the static property 
AntiForgeryConfig.UniqueClaimTypeIdentifier.

Exception Details: System.InvalidOperationException: A claim of type
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' or 
'http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider' was 
not present on the provided ClaimsIdentity. To enable anti-forgery token
support with claims-based authentication, please verify that the configured claims provider 
is providing both of these claims on the ClaimsIdentity instances it generates. 
If the configured claims provider instead uses a different claim type as a unique 
identifier, it can be configured by setting the static property 
AntiForgeryConfig.UniqueClaimTypeIdentifier.

Source Error:
Line 4:      using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new 
{ id = "logoutForm", @class = "navbar-right" }))
Line 5:      {
Line 6:      @Html.AntiForgeryToken()

POST Login action

// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }

    var claims = new List<Claim>
    {
        new Claim(ClaimTypes.Name, "Brock"),
        new Claim(ClaimTypes.Email, "brockallen@gmail.com")
    };
    var id = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);

    var ctx = Request.GetOwinContext();
    var authenticationManager = ctx.Authentication;
    authenticationManager.SignIn(id);

    return RedirectToAction("Welcome");
}

_LoginPartial.cshtml

@using Microsoft.AspNet.Identity
@if (Request.IsAuthenticated)
{
    using (Html.BeginForm("LogOff", "Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))
    {
    @Html.AntiForgeryToken()

    <ul class="nav navbar-nav navbar-right">
        <li>
            @Html.ActionLink("Hello " + User.Identity.GetUserName() + "!", "Index", "Manage", routeValues: null, htmlAttributes: new { title = "Manage" })
        </li>
        <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>
    </ul>
    }
}

I have tryed setting ClaimTypes.NameIdentifier (like in this SO answer)

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
}

And then I "only?" get this error

A claim of type 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' was 
not present on the provided ClaimsIdentity.

I want to keep the antiforgeryToken because it can help against cross-site scripting.