jeudi 30 juin 2016

Is there any roles authentication functionality built in to Windows Authentication in ASP.NET?

So I'd like to use Windows Authentication with a new ASP.NET MVC project, but I will probably need roles based authentication functionality so that users of the app can be designated different roles by the application (e.g. Administrator, Approver, General User).

Is there any roles-based authentication functionality built in to Windows Authentication in ASP.NET or do you just have to just manually build this in yourself?

Are there any good reporting options for ASP.NET MVC?

I've used ReportViewer with ASP.NET Web Forms and have heard of others that use Crystal Reports with Web Forms, but don't know of any good reporting options for ASP.NET MVC (I'm using MVC 4 and 5).

I need the ability to display report data in a nice table (e.g. pagination and maybe allow the user to select the results displayed per page) and also the ability for the user to export the report to the Excel and PDF formats.

What do you guys use for reports in MVC? Know of any good options?

How to create a string from c# that can show in View as a rendered anchor tag

I am trying to create a string in such a way that it should rendered as anchor tag in cshtml page.But instead of anchor tag, it is rendering as string and it shows the string as it is. Can somebody correct me please.

Here is what I am doing

string info= "You are on this page. <a target=_blank >Click to view</a>"

SharePoint Document Management

I am working with a document library but it has limited space. Can someone give me a idea to maximize storage space or in other words can anyone tell us what will be the ways of storing data?

mercredi 29 juin 2016

How to delete multiple records in a webgrid by clicking a delete button which is declared in a partial view in MVC

I have declared the webgrid inside a div in a partial view and my delete button is in Main View.Now I want a functionality in which when i click the delete button my webgrid should get refreshed only not whole page(Main View).

**I want to refresh only partial View which Contains webgrid using jquery in mvc

My partial View Code is as follows:

WebGrid grid = new WebGrid(source: Model, rowsPerPage: 10, canPage: true, defaultSort: "Station");

    //WebGrid grid = new WebGrid(source: Model, rowsPerPage: 10, canPage: true, defaultSort: "Station", ajaxUpdateContainerId: "grid1");

    string Message = "";

    if (@ViewBag.NoData != null)
        Message = ViewBag.NoData.ToString();

    <div id="UserMainDiv">
            @if (Model.Count() > 0)
                <div id="grid1" class="row container" style="width:84%;margin-left:8%;">

                    <div class="col-md-12" style="width:100%;color:black;margin-top:10px;padding-left:0px;padding-right:0px;">

          htmlAttributes: new { id = "grid" },
    tableStyle: "webgrid",
    headerStyle: "webgrid-header",
    footerStyle: "webgrid-footer",
    alternatingRowStyle: "webgrid-alternating-row",
    selectedRowStyle: "webgrid-selected-row",
    rowStyle: "webgrid-row-style",
          //mode: WebGridPagerModes.All,
          //firstText: "",
          //lastText: ">>",
          //previousText: "<",
          //nextText: ">",

          columns: grid.Columns
              //Here I am going to add checkbox column
              //Here I am going to add checkbox column
              grid.Column(format: @<text> <input type="checkbox" value="@item.ID" name="ids" /> </text>, header: "{checkall}"),
                @*grid.Column("Name",format: @<text>@Html.ActionLink((string)item.Name, "AddEdit", "gridchk", new { id = })</text>),*@
            grid.Column("Station", format: @<text>@Html.ActionLink((string)item.Station, "EditEmployee", "Manage", new { id = item.ID }, new { @class = "modal1" })</text>),
           grid.Column("FlightNo", "Flight No", format: @<text>@Html.ActionLink((string)item.FlightNo, "EditEmployee", "Manage", new { id = item.ID }, new { @class = "modal1" })</text>),
    grid.Column("FlightDate", "Flight Date", format: @<text>@Html.ActionLink((string)item.FlightDate.ToString("MM/dd/yy"), "EditEmployee", "Manage", new { id = item.ID }, new { @class = "modal1" })</text>),
    //grid.Column("FlightDate", "Flight Date", format: (item) => item.FlightDate != null ? item.FlightDate.ToString("MM/dd/yy") : "NULL"),
    grid.Column("PaxNo", "Pax No", format: @<text>@Html.ActionLink((string)item.PaxNo != null ? (string)item.PaxNo : "NULL", "EditEmployee", "Manage", new { id = item.ID }, new { @class = "modal1" })</text>),
    //grid.Column("PaxNo", "Pax No", format: (item) => item.PaxNo != null ? item.PaxNo : "NULL"),
    grid.Column("PaxNoOwnward", "PaxNo Onward", format: @<text>@Html.ActionLink((string)item.PaxNoOwnward != null ? (string)item.PaxNoOwnward : "NULL", "EditEmployee", "Manage", new { id = item.ID }, new { @class = "modal1" })</text>),
    //grid.Column("PaxNoOwnward", "PaxNo Onward", format: (item) => item.PaxNoOwnward != null ? item.PaxNoOwnward : "NULL"),
    grid.Column("TextMsg", format: @<text>@Html.ActionLink((string)item.TextMsg, "EditEmployee", "Manage", new { id = item.ID }, new { @class = "modal1" })</text>)



            <div style="width:80%;margin-left:10%;">
                <div class="row container">
                    <div class="col-md-12" style="width:100%;color:black;margin-top:10px;text-align:center;">

                        @Html.Label("", Message, new { id = "lblMessage" })



And My Main page view where i have delete button button code declared.

With that I am using Jquery

  $('#btnDelete').click(function (e) {
            var command = $('#btnDelete').val();
            var myArray = [];
            $("#gridtable tbody tr td:nth-child(1)").find('input[type="checkbox"]:checked').each(function () {


            var url = '@Url.Action("DeleteUser", "CreateUser")';

                url: url,
                type: 'GET',
                data: { ids: myArray },
                dataType: 'html',

                success: function (data) {
                   // $("#demoaArea").html(data);
                    // window.location.href = url;

                error: function (XMLHttpRequest, textStatus, errorThrown) {

                    //alert('error; ' + eval(error));
                    alert("Status: " + textStatus); alert("Error: " + errorThrown);



My Delete controller code:

public Actionresult DeleteStudent(int ids)
        // delete the record from ID and return true else false


Convert Amount To Letter in RDLC

I want to Convert Amount to Letters in RDLC Report.

for example : 100 in integers should be shown as "Hundred Rupees only".

mardi 28 juin 2016

How to use @Scripts in MVC3 VS10 application

I have a MVC3 application in Visual Studio 2010 . I need to refer the scripts/styles in layout page using following tag


But I am unable to use like this, since System.web,optimization is not available from _Layout.cshtml( even though the dll is referred in the project). how to resolve this?

How to delete multiple records in webgrid without refreshing whole page in MVC? Only Webgrid should refresh

I am making Some functionalities in my webgrid. When I select one or more than one checkbox to delete the data my page get refreshed.I wanted to have functionality in which My webgrid should refresh not all the webpage. Please help me guys.An link or any tutorial will seriously help me.

how can pass more than one query object to a view

i have an action named PackageIndex in which i am creating a list type view of package class this view i use layout in which i have to to display notification on navbar ...for that purpose i have to pass notification list to layout to display code is given below...

  public ActionResult PackageIndex()
            //feedback counter
            int count = feedbackCounter();
            ViewData["FeedbackCount"] = count;
            int notificationcount = notificationCounter();
            ViewData["notificationcount"] = notificationcount;
            return View(db.packages.ToList());

in this action i also have to passs (db.notification.ToList()) provide data to layout ..i can't understand how to solve this...

How to run a local IIS inside a Web Form project in Visual Studio 2013?

Is it possible to create a desktop application (with an executable file) through a "windows form" project in Visual Studio 2013?. Also, this application should include a "view" that can deploy another Web solution that I already did using MVC. The final users have no local IIS since and they are not allowed to install IIS in their Windows. Is this possible?

samedi 25 juin 2016

MVC C# Message read update

I am creating a message inbox system in MVC.

In my website, I will have notification span/label in the nav bar that alerts the user if they have an unread message (similar to this site's notifications on the top). If a user clicks on a message in his inbox that is unread, this will send a call to the database to update that messages column Read to false. How can I update the both the inbox and nav bar to show that I have one less message unread?

Do I go Ajax, javascript and if so what is the easiset way to accomplish this?

vendredi 24 juin 2016

Scope value does not reflect in the view

I really need your help... I have problem in updating scope in my ASP.Net MVC/AngularJS.

The issue with $scope.svFullName ... It does not reflect in the view when I change its value even though it is changing in the JS code because i have tested it from the js. Here is my code:


<td ng-repeat="x in supervisors | limitTo:1" style="width: 60%;">
<div ng-show="!svElements">@* *@</div>
<div ng-show="svElements">
    <select ng-model='svFullName' ng-selected='svFullName'>
        <option ng-repeat="z in supervisorsList"></option>
    <a href="javascript:void(0)">Save</a>                                                                                                

Edit Save


var myApp = angular.module('myApp', []);
myApp.controller('mainController', function ($scope, $http) {
    .then(function (response) {
        $scope.supervisors =;
        $scope.svFullName =[0].supervisorfName + " " +[0].supervisorlName;
        $scope.defaultsvFullName = $scope.svFullName;
    .catch(function (e) {
        console.log("error", e);
        throw e;
    .finally(function () {
        console.log("This finally block");

    .then(function (response) {
        $scope.supervisorsList =;
    .catch(function (e) {
        console.log("error", e);
        throw e;
    .finally(function () {
        console.log("This finally block");

$scope.svElements = false;
$scope.toggleSV = function () {
    if ($scope.svElements) {
        $scope.svFullName = $scope.defaultsvFullName;
    $scope.svElements = !$scope.svElements;

The $scope.svFullName is bonded with the div, so when I click on edit, and when I change the name, the $scope.svFullName will be changed... What I want to do is, changing back the $scope.svFullName to its default value when I click on cancel.

The value does not reflect in the view

MVC webgrid paging. On page change control values are lost

I am using MVC webgrid with paging. There is a column having a text box in the grid. When I change page, the value of this textbox is lost. I want to retain the textbox values even when page changes.

Extjs6 with

I have downloaded the Extjs6.0.2 and unzipped it, but having hard time including it in an empty mvc project. I have some experience with versions 3 and 4 of ExtJS, in which I just included everything in the project (ext-all.js and the styles), now I am not sure which files should I include (especially confused on the styles).

So I appreciate if you can point out what files/folders from the trial package should be included in an asp-net-mvc project.

jeudi 23 juin 2016

Get values multi output parameter ( Store procedure ) in MVC

My store procedure :

create PROCEDURE [dbo].[GetProduct]

@ProdId int output

@ProdCode nvarchar(20) output

as begin set @ProdId=1 set @ProdCode='PROD00001' end

When i call SP GetProduct in Action, How to get values of 2 output parameter(@prodId,@ProdCode) ?

Search in all tables

My problem is I dont know how to Search in all tables and I have no idea. Just one textbox such as YouTube, results will be written in the source. Can someone give me an idea? I would be very pleased. I have to do it on the MVC

Typeahead not populates value

I am using typeahead where i am using ajax call to fetch data from controller. I am getting data in OnSuccess method but it's not populating. Below is my code:

        hint: true,
        highlight: true,
        minLength: 1
        limit: 12,
        async: true,
        source: function (query, process) {
            return $.ajax({
                url: "/Home/GetJsonData",
                type: 'POST',
                data: { query: query },
                dataType: 'json',
                success: function (json) {
                    var matches = [];
                    $.each(json, function (i, str) {
                    return process(matches);
<input type="text" id="search-input" class="form-control" />

How do i achieve the same?

mercredi 22 juin 2016

"InvalidOperationException" Exceptions while Creating MVC Web API

I am trying to create a MVC API using repository pattern. Following is my code


namespace InformationServices.DAL
    public interface IInsurerDAL
        Task<DataTable> GetInsurer(string cover,string version);


namespace InformationServices.DAL
    public class InsurerDAL : IInsurerDAL
        int commandTimeout;

    public InsurerDAL()
        Int32.TryParse(ConfigurationManager.AppSettings["CommandTimeout"], out commandTimeout);
        if (commandTimeout <= 0)
            commandTimeout = 30;
    public async Task<DataTable> GetInsurer(string cover, string version)
                //some code 


namespace InformationServices.Repository
    public interface IInsurerRepository
        ConsumerDetails ConsumerDetails { get; set; }
        Task<ResponseModel<Insurer>> GetInsurer(string cover, string version);


namespace InformationServices.Repository
    public class InsurerRepository : IInsurerRepository, IDisposable
        InsurerDAL oInsurerDAL;
        ConsumerDetails oConsumerDetails { get; set; }

        public ConsumerDetails ConsumerDetails
                return oConsumerDetails;
                oConsumerDetails = value;

        public InsurerRepository()
            var container = new UnityContainer();
            oInsurerDAL = container.Resolve<InsurerDAL>();

            MapperRegistry.Mappers.Add(new DataReaderMapper());

            //To load the DataReaderMapper before we actually use it.
            var type = typeof(DataReaderMapper);
        public async Task<ResponseModel<Insurer>> GetInsurer(string cover, string version)

        //Implementation of IDisposable interfase.
        protected void Dispose(bool disposing)
            if (disposing)
                if (oInsurerDAL != null)
                    oInsurerDAL = null;

        public void Dispose()


    namespace InformationServices.API.Controllers
    public class InsurerController : ApiController
    private IInsurerRepository InsurerRepository;

    private static ILog logger = log4net.LogManager.GetLogger(typeof(InsurerController));

    public InsurerController(IInsurerRepository repository)
        InsurerRepository = repository;
        InsurerRepository.ConsumerDetails = CommonFunctions.FetchConsumerDataFromHeader();

    public async Task<IHttpActionResult> GetInsurer(string cover, string version, string srcKey)
    //code here


I am also using following code to register it with a container

var container = new UnityContainer();
container.RegisterType<IInsurerDAL, InsurerDAL>(new HierarchicalLifetimeManager());
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);

still I am getting following issue when I try to use this Web API :

Resolution of the dependency failed, type = \"InformationServices.API.Controllers.InsurerController\", name = \"(none)\".\r\nException occurred while: while resolving.\r\nException is: InvalidOperationException - The current type, InformationServices.Repository.IInsurerRepository, is an interface and cannot be constructed. Are you missing a type mapping?

Mvc Music Store (MVC3) : SampleData won't populate DB

Here's my really BIG problem: When I run the program it finds NO genres ): Check the picture

The example is using this code as the connection string:

    <add name="MusicStoreEntities"
    connectionString="Data Source=|DataDirectory|MvcMusicStore.sdf"

As you might notice, It is using SqlServerCe4.0, but instead I change it in order to use SqlClient (wich I have already installed):

             connectionString="Data Source=(localdb)\v11.0;
             Integrated Security=true;AttachDbFileName=|DataDirectory|MvcMusicStore.mdf"

Sample Data file:

using System.Collections.Generic;
using System.Linq;
using System.Data.Entity;

namespace MvcMusicStore.Models
    public class SampleData : DropCreateDatabaseIfModelChanges<MusicStoreEntities>
        protected override void Seed(MusicStoreEntities context)
            var genres = new List<Genre>
                //Perfec genres

            var artists = new List<Artist>
                //Cool Artists list

            new List<Album>
                //Awesome albums
            }.ForEach(a => context.Albums.Add(a));


A context class:

using System.Data.Entity;

namespace MvcMusicStore.Models
    public class MusicStoreEntities : DbContext
        public DbSet<Album> Albums { get; set; }
        public DbSet<Genre> Genres { get; set; }

Application Start class:

using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace MvcMusicStore
    public class MvcApplication : System.Web.HttpApplication
        protected void Application_Start()
            System.Data.Entity.Database.SetInitializer(new MvcMusicStore.Models.SampleData());



Any ideas of how to solve this problem? I'd appriciate your help.

ASP.Net MVC3, Convert existing MVC project into an AREA

I have a few separate ASP.Net MVC3 applications. Currently we want all these separate MVC projects to be made as AREAS under a new MVC project. It's like creating a central portal from where all these applications will be launched.

I need to know if there is a standard process in making these MVC projects as areas.

And what are the things that I need to worry about.

Thanks in advance.

XML fails after adding noNamespaceSchemaLocation

I am completely newby for XML and XML Schema namespaces. One of our delegates added xsi:noNamespaceSchemaLocation attribute on root node of our XML schema file, saying that they are validating XML before sending to us.

Now file with this attribute failing to load with in our website, and throwing below error.

There is an error with loading the xml data. Please ensure that the following text exists on the second line of the xml file: "xmlns="" " 'yyy' is an undeclared prefix. Line 1, position 149.

Whereas, xmlns attribute already exist on given place, but with sursprise the name of file being bit different. And there is nothing like 'yyy' in entire xml file.

If I remove xsi:noNamespaceSchemaLocation then file loads perfectly fine. I am not sure, why adding xsi:noNamespaceSchemaLocation makes file to load, and what I can do to resolve it.

Hopefully, I have provided all information required for this issue. This is all at this moment I can think to mention.

Can anybody please help me to enlighten me on this??

mardi 21 juin 2016

Get days that are not present in a date range using Linq

I got a list of dates that serves as attendance like


and i have this date range


How would i get the dates that are not on the list but falls in the date range using linq..

jQuery MVC Controller return error

I have an ASP.NET MVC3 app and a button in the following view that is supposed to send the drop down values from two kendo drop down lists to a control method. I have writen a jQuery function to send the data as follows in the View file:

    $("#get").click(function () {
        alert('Thank you! You picked:\n\nAsset1: ' + dropdownVals.first_asset + '\n\n ' + 'and\n\n' + ' Second Asset: ' + dropdownVals.second_asset);
            type: "POST",
            url: "/Asset/RunPy", // the method we are calling
            contentType: "application/json",
            data: {as_1: dropdownVals.first_asset, as_2: dropdownVals.second_asset},
            dataType: "json",
            success: function (result) {
                alert('Yay! It worked!');
                // Or if you are returning something
                alert('I returned... ' + result.WhateverIsReturning);
            error: function (result) {
                alert('Oh no :(');

Going to the following Controller:

        public ActionResult RunPy(String as_1, String as_2)
            String cmd = "C:/Program Files (x86)/Python27/python.exe";
            String argss = "C:/My_Python_lib/ joe bill";
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = cmd;
            start.Arguments = argss;
            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;
            using (Process process = Process.Start(start))
                using (StreamReader reader = process.StandardOutput)
                    string result = reader.ReadToEnd();
                    List<string> resultList = new List<string>();

                    return Json(new { success = true });




I don't know where the issue is arising but, the error event in the jQuery function is firing up.

However, if I call the same Controller method using another button class as follows, then I get no errors.

<form class="float_left" action="RunPy" method="post">
    <button class="btn btn-inverse" title="Connect" type="submit">Make Connection</button>

how to create action for mulitple view button (submit) in one controller in MVC

I am not able to perform action for button from second view, my folder path look like this


In one controller I create 2 action one is Login and another is home... and in Login view I created button when I click it take to the controller,

but when I click form home view it does nothing...

samedi 18 juin 2016 Mvc: How i can save state of my web page where last time time close it.?

I wanted to save webpage state where user close that page last time .When user came again to my website automatically redirect to that page.

How To Replace < with < and >

Hi guys,

    function getData() {
            var tbody = document.createElement("tbody");
            var table = document.getElementById("table");
        tbody.innerHTML = @ViewBag.customerDetails;        

That's my code and the problem is i am setting my ViewBag.customerDetails very nice HTML in my controller but some reason in the View part i am getting my InnerHtml like,

&lt;tr&gt;&lt;td&gt;5&lt;/td&gt;&lt;td&gt;5&lt;/td&gt;&lt;td&gt;alkan&lt;/td&gt;&lt;td&gt;akkaya&lt;/td&gt;&lt;td&gt;10.05.2016&lt;/td&gt;&lt;td&gt;31.05.2016&lt;/td&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;6&lt;/td&gt;&lt;td&gt;6&lt;/td&gt;&lt;td&gt;UFUK&lt;/td&gt;&lt;td&gt;DOGAN&lt;/td&gt;&lt;td&gt;30.06.2016&lt;/td&gt;&lt;td&gt;31.07.2016&lt;/td&gt;&lt;td&gt;1231&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;7&lt;/td&gt;&lt;td&gt;7&lt;/td&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;27.06.2016&lt;/td&gt;&lt;td&gt;27.06.2016&lt;/td&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;8&lt;/td&gt;&lt;td&gt;8&lt;/td&gt;&lt;td&gt;4&lt;/td&gt;&lt;td&gt;4&lt;/td&gt;&lt;td&gt;27.06.2016&lt;/td&gt;&lt;td&gt;27.06.2016&lt;/td&gt;&lt;td&gt;4&lt;/td&gt;&lt;td&gt;&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;9&lt;/td&gt;&lt;td&gt;9&lt;/td&gt;&lt;td&gt;24&lt;/td&gt;&lt;td&gt;32&lt;/td&gt;&lt;td&gt;27.06.2016&lt;/td&gt;&lt;td&gt;27.06.2016&lt;/td&gt;&lt;td&gt;3&lt;/td&gt;&lt;td&gt;200 &lt;/td&gt;&lt;/tr&gt;;

I searched it google and stackoverflow, i tried every suggestions but it doesn't work. Can someone help me?

Thanks a lot.

No way to resolve conflict - error with Razor MVC

When I compile my project I get errors with my razor as per the following:

1>------ Build started: Project: Icent.RIME.Web, Configuration: Debug Any CPU ------
1>  No way to resolve conflict between "System.Web.Razor, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" and "System.Web.Razor, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35". Choosing "System.Web.Razor, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" arbitrarily.
1>  No way to resolve conflict between "System.Web.WebPages.Deployment, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" and "System.Web.WebPages.Deployment, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35". Choosing "System.Web.WebPages.Deployment, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" arbitrarily.
1>  Consider app.config remapping of assembly "System.Web.Razor, Culture=neutral, PublicKeyToken=31bf3856ad364e35" from Version "" [c:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies\System.Web.Razor.dll] to Version "" [C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v2.0\Assemblies\System.Web.Razor.dll] to solve conflict and get rid of warning.
1>  Consider app.config remapping of assembly "System.Web.WebPages.Deployment, Culture=neutral, PublicKeyToken=31bf3856ad364e35" from Version "" [c:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies\System.Web.WebPages.Deployment.dll] to Version "" [C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v2.0\Assemblies\System.Web.WebPages.Deployment.dll] to solve conflict and get rid of warning.
1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(1819,5): warning MSB3247: Found conflicts between different versions of the same dependent assembly. In Visual Studio, double-click this warning (or select it and press Enter) to fix the conflicts; otherwise, add the following binding redirects to the "runtime" node in the application configuration file: <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="System.Web.Razor" culture="neutral" publicKeyToken="31bf3856ad364e35" /><bindingRedirect oldVersion="" newVersion="" /></dependentAssembly></assemblyBinding><assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="System.Web.WebPages.Deployment" culture="neutral" publicKeyToken="31bf3856ad364e35" /><bindingRedirect oldVersion="" newVersion="" /></dependentAssembly></assemblyBinding>
1>C:\Program Files (x86)\MSBuild\14.0\bin\Microsoft.Common.CurrentVersion.targets(1819,5): warning MSB3277: Found conflicts between different versions of the same dependent assembly that could not be resolved.  These reference conflicts are listed in the build log when log verbosity is set to detailed.
1>  Icent.RIME.Web -> C:\Users\mkiriko\Documents\rime_au_webapp\Icentric.RIME.Web\bin\Icentric.RIME.Web.dll
========== Build: 1 succeeded, 0 failed, 10 up-to-date, 0 skipped ==========

When I look at my views all razor methods such as @Url.Action(..) have error "The name 'url' does not exist in the current context.

My web.config in Views folder looks like the following:

    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />

    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <!--   <add namespace="Telerik.Web.Mvc"/>
        <add namespace="Telerik.Web.Mvc.UI"/> -->

How can I fix this error? My project is old and uses MVC3

vendredi 17 juin 2016

What do the `%%` (two percentage) characters mean in ASP.NET Razor MVC renderer?

What do these %% (two percentage characters) means in ASP.NET Razor MVC renderer?

    ViewBag.Title = %%Index%%;

Error when trying to connect to SQL Server from program on remote computer

I am trying to set up a system for employees to use in the office so they can run certain programs from a website.

They will be able to login and go to a reports page an click a button to run a reports program on the utility server. The program will connect to SQL Server to get the login information and then login to another site and programmatically create the reports and download them.

I have the website trying to run the program but it is terminated due to an unhandled exception. here is the stack trace from the error in the event viewer.

Application: Trending Reports.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.Data.SqlClient.SqlException

Stack: at System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(System.Data.Common.DbConnection, System.Data.ProviderBase.DbConnectionFactory, System.Threading.Tasks.TaskCompletionSource1<System.Data.ProviderBase.DbConnectionInternal>, System.Data.Common.DbConnectionOptions) at System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(System.Data.Common.DbConnection, System.Data.ProviderBase.DbConnectionFactory, System.Threading.Tasks.TaskCompletionSource1, System.Data.Common.DbConnectionOptions) at System.Data.SqlClient.SqlConnection.TryOpenInner(System.Threading.Tasks.TaskCompletionSource1<System.Data.ProviderBase.DbConnectionInternal>) at System.Data.SqlClient.SqlConnection.TryOpen(System.Threading.Tasks.TaskCompletionSource1) at System.Data.SqlClient.SqlConnection.Open() at Trending_Reports.Program.Main(System.String[])

Here is the code I am using to start the program.

var processToRun = new[] { @"D:\test\Trending Reports.exe" };

var connection = new ConnectionOptions();
connection.Impersonation = System.Management.ImpersonationLevel.Impersonate;
connection.Username = "Username";
connection.Password = "password";

var wmiScope = new ManagementScope(String.Format("\\\\{0}\\root\\cimv2", "Server"), connection);

var wmiProcess = new ManagementClass(wmiScope, new ManagementPath("Win32_Process"), new ObjectGetOptions());
wmiProcess.InvokeMethod("Create", processToRun);

The program itself is using multi-threading. Could this be causing the issue? Or could it be a user issue to where its not using my user profile on the remote computer?

LineControl Editor Copy from Word document Issue

I have used LineControl editor and when I try to copy paste the content from Word document. The editor gets broken.First view looks like this

then after saving and refreshing the page. it gets broken like this.

In View :

      <h4>Edit description</h4> <hr />                   
                         <textarea rows="4" cols="20" id="txtEditor"> </textarea> 
                         <div class="button-bar row center">

                            <input type="button" id="submit" class="btn btn-info" onclick="Submit()" value="Submit" />
                            <button type="button" class="btn btn-info" onclick="cancelAdd()">Cancel</button>

     <div id="desctext">

Inside script tags

  function Submit() {
    var Id = $("#hiddendomainId").val();
    var values = $(".Editor-editor").html();

        url: '/Domain/updateDescription',
        dataType: 'json',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',

        data: JSON.stringify({ id: Id, description: values }),
        success: function (response) {
            if (response.success) {


        error: function (val) {
            $("#DevMessage").html('<div>Error in returning </div>');
            $("#DevMessage").addClass("alert alert-danger");
 function showContent(){

$(document).ready(function () {


Thanks in advance.

Model is null after postback in pager

On my page I have:

  • a 'filter' section - a couple of checkboxes and textboxes,
  • a 'search' button,
  • grid with paging where the results are displayed. The grid is from Telerik (, but I don't think this matters.

Searching works OK - I can input some text or check a checkbox in the filter section and the appropriate results are displayed.

Paging works OK only if I use it when the page is loaded (that means before I click Search button, in this case the url is '...Home').

But if click search first (in this case the url will become '...Home/Search') and then try to go to another page on the grid then I get an exception in the Search method, because the model.Filter parameter is null (System.NullReferenceException: Object reference not set to an instance of an object.)

I tried to solve the problem in many different ways (with RedirectToAction method, storing the filter to session and use it in Search method,...) but no solution worked in all scenarios. Any ideas?

My simplified code:


public ActionResult Index()
    ViewBag.Results = GetResults(filter);
    return View(new HomeModel { Filter = filter });

public ActionResult Search(HomeModel model)
    ViewBag.Results = GetResults(model.Filter);
    return View("Index");

public class OverviewFilterModel
    public bool Type1 { get; set; }
    public bool Type2 { get; set; }
    public string WorkingOrder { get; set; }


@using (Html.BeginForm("Search", "Home", FormMethod.Post, new { @class = "form-inline" }))
    <div class="form-group" style="margin-left: 135px;">
        @Html.CheckBoxFor(p => p.Filter.Type1)@Html.LabelFor(p => p.Filter.Type1, new { style = "margin: 0 15px 0 5px;" })
    <!-- a bunch of other checkboxes -->
    <br />
    <div class="form-group">
        <label style="width: 130px; text-align: right;">Delovni nalog</label>
        @Html.TextBoxFor(p => p.Filter.WorkingOrder, new { @class = "form-control ecert-filter-small", @autocomplete = "off" })
    <!-- a bunch of other textboxes -->
    <button class="k-button" id="button-refresh" style="margin: 10px 0 0 135px;">Refresh</button>
    <hr />
        .Events(p => p.Change("overviewOnRowSelect"))
        .Columns(columns =>
            columns.Template(@<text>@Html.ActionLink("WorkingOrder", "Index", "WO", new { dn = @item.WorkingOrder }, new { @class = "selectable-dn" })</text>).Title("");
            columns.Bound(p => p.Type);
            columns.Bound(p => p.WorkingOrder);
            columns.Bound(p => p.Date);
            columns.Bound(p => p.ProductId);
            columns.Bound(p => p.ProductName);
        .Pageable(p => p
            .Messages(q =>
                q.Display("{0} - {1} od {2} records");
                q.Empty("No data for selected filter");
                q.ItemsPerPage("Number of records per page");
        .DataSource(p => p.Server().PageSize(20).Model(q => { q.Id(r => r.WorkingOrder); }))

jeudi 16 juin 2016

A generic error occurred in GDI+ with iTextSharp, only on a particular server

Most of the questions about this error (and wow, there are a lot) revolve around saving to a file, which isn't what I'm doing.

My code is as follows - .NET 4.5, MVC3, IIS7.5, Win2008R2:

string fileName = /* something.png */;
string imageLocation = HttpContext.Current.Server.MapPath(
    string.Format(@"~/Content/images/{0}", fileName));

var image = iTextSharp.text.Image.GetInstance(

Decompiling iTextSharp, the GetInstance method looks like:

public static Image GetInstance(Image image, ImageFormat format)
    MemoryStream memoryStream = new MemoryStream();

    image.Save(memoryStream, format); // <-- Exception here

    return Image.GetInstance(memoryStream.ToArray());

The exception I get is:

System.Runtime.InteropServices.ExternalException (0x80004005):

A generic error occurred in GDI+.

at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder, EncoderParameters encoderParams)

at iTextSharp.text.Image.GetInstance(Image image, ImageFormat format)

So it's failing when attempting to save the image into a MemoryStream, not to a file or the HTTP response.

This just started happening to an existing application that worked fine previously. The exact same code functions perfectly on a different server and my local machine (all 3 are 2008R2), and it happens to every application on my production server (I have 4), and also even a brand new one with the same codebase I put up there for testing this issue.

So I assume there's something with my specific production server, maybe IIS. Windows updates seem to be the same between the two servers, so I don't think that's it.

Anything else that you can think of which might be environment-specific to cause this error? I can re-work the code to clean up our part a bit, like creating a new in-memory image instead of using the one created from the file, but since this is my production system, I'd rather find a short-term solution without a code-fix.

Setting up URL Rewrite rule for a specific domain SEO

On Google there is the following Url

So now my page is now available in multi language and i have now the language in the url, and it looks like this

So I will redirect all old links with url rewrite in the web.config, but I can't find out the match condition to find out if there is a languege insite the url.

My role:

<rule name="" >
  <match url="(.*)" />
  <conditions logicalGrouping="MatchAll">
    <add input="{HTTP_HOST}" pattern="^(localhost:3005/|localhost:3005/)$" />
 <action type="Redirect" url="http://localhost:3005/de/{R:1}" logRewrittenUrl="true" />

Thanks for any help!

Begin Form firing HTTPGET instead of HTTPPOST in mVc please help me with this

Begin form from view after submission calls httpGET instead of HTTPPOST even submit and every thing are inside @begin form.

HTTP PUT is not working in ASP.NET Web API

I have simple Web API controller in which GET and POST are working but PUT and DELETE is not working. Server throws The requested resource does not support http method 'PUT' error when accessing PUT and DELETE Here is how web.config looks like:

<?xml version="1.0" encoding="utf-8"?>
            <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
            <compilation debug="true" targetFramework="4.5.2">
                    <add assembly="System.Data.Entity, Version=, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
            <httpRuntime targetFramework="4.5.2" />
                <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
            <validation validateIntegratedModeConfiguration="false" />
                <remove name="ApplicationInsightsWebTracking" />
                <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
                <remove name="ExtensionlessUrlHandler-Integrated-4.0" />      
                <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
            <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
                    <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
                    <bindingRedirect oldVersion="" newVersion="" />
                    <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
                    <bindingRedirect oldVersion="" newVersion="" />
                <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
                <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" />

Code for Global.asax

protected void Application_Start(object sender, EventArgs e)

Code for Web API Configuration

public static void Register(HttpConfiguration config)
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{Id}",
            defaults: new { Id = RouteParameter.Optional }

And the controller has...

public class GroupsController : ApiController
    public ActionResult Put(int Id, [FromBody]Group NewGroup)
        //some code here

I have also looked into online resource but none of those are helping out... here and here

I'm trying to make this API working in developer machine (IIS express/compact one that ships with Visual Studio).

when i call Image its showing binary code

I'm using Generic Handler in to display image its working great but when i open image in new tab i.e


In new Tab its showing binary code but i want to display Image how to achieve this below is my code i'm using in my Generic Hander (ImageHandler.ashx.cs)

public void ProcessRequest(HttpContext context)
  string ID = context.Request.QueryString["ImageID"];
  if (ID!= "")
   SqlConnection connection = new SqlConnection("Server=.; Database=master; User Id=sa; Password=tiger;");
   SqlCommand cmd = new SqlCommand("[spGetImage]", connection);
   cmd.CommandType = CommandType.StoredProcedure;
   cmd.Parameters.AddWithValue("@imgID", ID);
   SqlDataAdapter da = new SqlDataAdapter(cmd);
   DataSet ds = new DataSet();
   //Get Image Data
   byte[] file = null;
   if (ds.Tables[0].Rows.Count > 0)
     file = (byte[])ds.Tables[0].Rows[0]["img"];

    MemoryStream memoryStream = new MemoryStream();
    memoryStream.Write(file, 0, file.Length);
    System.Drawing.Bitmap _bitMap = new System.Drawing.Bitmap(memoryStream);
    context.Response.Buffer = true;

mercredi 15 juin 2016

Sending string from [HttpPost] Web Api and read it as int in MVC

I'm making an [HttpPost] Web Api that executes a stored procedure that inserts an object in DB then retrieves its created ID, then I'm consuming this service in an MVC website. The sent ID is always 0, how can I get the right value?

mysql random records give a duplicate data

I am developing a website where records are not sequential, records are displayed randomly. I use simple mysql random method to display random records by using rand() with limit where limit is parameterized to get next record one by one.

I am using mvc framework and mysql database.

Here is mysql query.

select distinct
    registration lw
        left join
    states st ON st.Id = lw.State_Id
        left join
    city ct ON = lw.City_Id
        left join
    total_views lwv ON lwv.l_id = lw.L_id
        left join
    rsuper rsub ON rsub.l_id = lw.L_Id
        left join
    lfilter fl ON fl.L_Id = lw.L_Id
    lw.City_Id = '577'
        and rsub.special_id = 1
        and lw.status = 'Active'
        and lw.L_id != 1
        and lw.service = 'Free'
order by rand()
limit start , pageSize

in this query pageSize is total number of record which is 18 and start variable is change according to parameter but default value is 0.

It gives 18 records randomly on ajax request but problem is that it gives some duplicate records.

please tell me how to prevent this or other better solution for it and i also try other alternatives of rand() function but it not helps me. I used this tutorial for better improvements in random records.

mardi 14 juin 2016

Mobile number model Regular Expression to validate mobile no greterthen 0 with fixed digit length 10 (MVC 5)

currently i am using code below, but not able to add validate > 0 currently its not validate 0000000000

[RegularExpression(@"(\b\d{3}[-.]?\d{3}[-.]?\d{4}\b)", ErrorMessage = "Please enter valid mobile no.!")]

Scan QR Code Sync to a System?

How to do it? It is possible that a scanned qr code from android phone will detect by a web system?. If possible please tell me how. Thanks all.

The report definition is not valid. (ReportViewer.Common: 12) Details: The report definition has an invalid target namespace which cannot be upgraded

I am developing an application in MVC 3 and one of my RDLC report bases on (ReportViewer2015) dlls.

How can i fix this issue ?

I am getting this exeption

The report definition is not valid. Details: The report definition has an invalid target namespace '' which cannot be upgraded.

Unable to call webservice function angularjs

Unable to call webservice function from angularjs controller. It is accessing the file but function is not accessible. Errors:

  1. server responded with a status of 500 (Internal Server Error)
  2. System.InvalidOperationException:Web Service method name is not valid. at System.Web.Services.Protocols.HttpServerProtocol.Initialize() at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)

    namespace AngularJSTesting.App{

    [WebService(Namespace = "")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
    public class WebService2 : System.Web.Services.WebService
        string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["TextItConnectionString"].ToString();
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public string FetchData()
            DataTable dt = new DataTable();
            using (SqlConnection con = new SqlConnection(connectionString))
                using (SqlCommand cmd = new SqlCommand("select UserName, Name, Email, PhoneNumber from new_users where UserId < 11 order by UserId asc ", con))
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                    List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
                    Dictionary<string, object> row;
                    foreach (DataRow dr in dt.Rows)
                        row = new Dictionary<string, object>();
                        foreach (DataColumn col in dt.Columns)
                            row.Add(col.ColumnName, dr[col]);
                    return serializer.Serialize(rows);
       // [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string read()
            return "test";


js file

'use strict';

app.controller('aboutController', function ($scope, $http) {
$scope.message = "Now viewing About!";

var url = '';
           .success(function (data) {
               $scope.users = data;

           .error(function (data) {

lundi 13 juin 2016

How can the web system detect the scanned QR Code from android phone?

Hello everyone I am new in mvc3 c#. I have a web system that can produce a QR Code that can send into a email. My problem now is if the QR Code printed and scanned using my android phone. The web system must detect the data and register the people/employee to a certain event like Training Programs or Meetings. Thanks for the help.

Auto refresh token every 30 minutes - Oauth2

I have a Web API in server 1 , and Web MVC in server 2 (consume Web API ).I use Oauth2 with access token , refresh token follow : link here

In the demo of this Tut, when refresh a token Author use button : "Refresh Token" . But i don't want to do it, i want Web MVC auto send request (refresh token) to Web API every 30 minutes.

I have a simple system using QR Code. c# mvc3

i am having a trouble finding a solution for my problem. i am planning to scan the QR Code from my android phone and it will read on my system (add/search data). if anyone knows how please help i appreciate your answers. thanks a lot.

adding dropdown list with selected value from database

how to get the selected drown drop value from database..i'm storing employee details in one table with drop down selected value(integer) and in other table drop down value and text.

my models arepublic class EmployeeDetails { public int empid {set;get;} public string empname{set;get;} public string empdesig{set;get;} public decimal empsal{set;get;} public int education{set;get;} public DateTime time{set;get;} public string dropdownname { set; get; } }

 public class DropDownList
    public int dropdownId { set; get; }
    public string dropdownName { set; get; }

}` public class DisplayEmployeeViewModel
    public IEnumerable<EmployeeDetails> EmployeeDetails { set; get; }

    public DisplayCreateEmployeeViewModel createemployee { set; get; }

    public string TabName { set; get; }
    public List<SelectListItem> DropdownSelectListItems
            var dropdown = (new DropdownRepository()).GetDropdownTypes();
            var entityList = dropdown.Select(x => new SelectListItem()
                Text = x.dropdownName,
                Value = x.dropdownId.ToString()
            return entityList.ToList();


}` public class DisplayCreateEmployeeViewModel
    public EmployeeDetails EmployeeDetails { set; get; }
    public int empid { set; get; }
    public string empname { set; get; }
    public string empdesig { set; get; }
    public decimal empsal { set; get; }
    public int education { set; get; }
    public DateTime time { set; get; }
    public string dropdownname { set; get; }

    public List<SelectListItem> DropdownSelectListItems
            var dropdown = (new DropdownRepository()).GetDropdownTypes();
            var entityList = dropdown.Select(x => new SelectListItem()
                Text = x.dropdownName,
                Value = x.dropdownId.ToString()
            return entityList.ToList();

}` <div>
                <table id="tblemployeedetails" class="table table-hover table-bordered table-responsive "  >
                       <thead style="background-color:black;color:white; ">
                               <th>Employee Name</th>
                               <th>Employee Designation</th>
                               <th>Enployee Education</th>
                               <th>Employee Salary</th>

                        @foreach (EmployeeDetails details in Model.EmployeeDetails)
                                <td>@Html.CheckBox("status" + details.empid, new {value=details.empid,@class="detailCheckBox" })</td>
                                <td>@Html.TextBox(details.empname, details.empname, new {@class="txtdisable" })</td>
                                <td>@Html.TextBox(details.empdesig, details.empdesig, new { @class = "txtdisable" })</td>
                                <td>@Html.DropDownList(,Model.DropdownSelectListItems, new { @class = "txtdisable" })</td>
                                <td>@Html.TextBox(details.empsal.ToString(), details.empsal, new { @class = "txtdisable" })</td>




the code which i'm showing fetching the drop down complete list and showing. here i'm getting the list of drop down.But i want to get the list with selected text( stored value should select)

how to do that

dimanche 12 juin 2016

The remote server returned an error: (500) Internal Server Error. Web API

below code i use to post method from a page but give me an error.. thanks in advance. anyone have an idea or similar to my problem? please share

public ActionResult SaveNameAPI(string username, string password) {

        bool isValid = false;
        HttpWebRequest hwrequest;
        HttpWebResponse hwresponse;
        string POSTdata = null;
        string responseData = "";
        HttpClient client = new HttpClient();
        HttpWebResponse response;
        Stream postStream;

        string url = "(URL).asmx?op=ValidateLogin?username=" + username + "&password=" + password;

        hwrequest = (HttpWebRequest)WebRequest.Create(url);
        hwrequest.Accept = "*/*";
        hwrequest.AllowAutoRedirect = true;
        hwrequest.UserAgent = "http_requester/0.1";
        hwrequest.Timeout = 60000;
        hwrequest.Method = "POST";

        byte[] byteData;
        if (hwrequest.Method == "POST")
            hwrequest.ContentType = "text/xml";
            System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();              

            POSTdata = "username=" + username + "&password=" + password;
            byteData = encoding.GetBytes(POSTdata); 
            hwrequest.ContentLength = byteData.Length;
            postStream = hwrequest.GetRequestStream();
            postStream.Write(byteData, 0, byteData.Length);
            response = (HttpWebResponse)hwrequest.GetResponse(); <<-- this line gives me an error
        hwresponse = (HttpWebResponse)hwrequest.GetResponse();
        if (hwresponse.StatusCode == System.Net.HttpStatusCode.OK)
            StreamReader responseStream = new StreamReader(hwresponse.GetResponseStream());
            responseData = responseStream.ReadToEnd();
        var result = new JsonResult();
        result.Data = new
            username= username,
            password= password

        return result;


Checking and unchecking checkboxes with dynamic ids and class using jquery

I have below HTML which I am using to create a Grid. The grid has grouping i.e the grid shows products of each group. So, the grid structure has GroupName and a checkbox with it in the first row and then it follows some rows which shows products which are under that group with each having a checkbox too.

Same way I will have some other groups and their products which I am binding like below. As each product list have its group name on top. I want a functionality where I can be able to click on header group checbox and then all the items under that group will be checked and vice versa. Also If I check all the subitems one by one, Group header checkbox should automatically checked true. I have set the same class for main group checkbox and all its sub items.

    if (Model.ListOfGroups.Count() > 0)
            <td>Group Name</td>
            <td>Category Name</td>
            <td>SubCategory Name</td>
            <td>Release Date</td>
        @foreach (var obj in Model.ListOfGroups)
                    <input type="checkbox" class="cls@(obj.GroupId)" name="@obj.GroupId" onclick="checkUncheckAll(this.class)" />
            foreach (var objList in Model.ListOfProducts)
                if (objList.groupid == obj.GroupId)
                    <input type="checkbox" class="cls@(obj.GroupId)" name="@obj.GroupId" /></td>
                <td>@(Html.Kendo().DatePicker().Name(@objList.pkID + "datepicker"))</td>


<input type="button" value="Save" onclick="PickAllCheckedRows();" />

I have been trying to do this like below but no success. Also I want to pick all the checked group and its subitems on click of save button. Any help would be really appreciated.

<script type="text/javascript">
    function checkUncheckAll(sender) {
        var chkElements = document.getElementsByClassName('chkItems');
        for (var i = 0; i < chkElements.length; i++) {
            chkElements[i].checked = sender.checked;

  function PickAllCheckedRows() {

samedi 11 juin 2016

Redirection using javascript

I have a mvc 5 application in which I'd like to perform a redirection using javascript

 var sPageURL = decodeURIComponent(window.location);
 var lengthUrl = sPageURL.split('/').length;
 var NewUrl='';
 sPageURL.split('/').forEach(function (item, index) { 
            if (index < lengthUrl - 2) NewUrl += item;
                 if (index == lengthUrl - 1) {
                      if (item == "Organisateur") NewUrl += sPageURL.split('/')[lengthUrl - 2];
 window.location = NewUrl; 

I get as output :



The problem is that the new url is concatenated with the old one, I'd like that http://localhost:31569/Event/2 be replaced by localhost:31569.

I tried window.location = , window.location.href = and window.location.replace and I get the same result .

So I need to know :

  1. What is the reason of this problem ?
  2. How can I fix it?

Sending int from [HttpPost] Web Api and read it as int in MVC

I'm making an [HttpPost] Web Api that executes a stored procedure that inserts an object in DB then retrieves its created ID, then I'm consuming this service in an MVC website. The sent ID is always 0, how can I get the right value?

vendredi 10 juin 2016

Dynamic routing from database in MVC 3

In my application I have stored seo- friendly URLs in database. I want that all the URLs to be mapped to same controller/action with URL name as parameter.

URL I want to show is{URL} E.g. tuition/mathematics tuition *URL stored in database is - general tuition/mathematics tuition

I am unable to create route in global.asax please help.

What I am doing in global.asax is:

routes.MapRoute( "Class",
new { controller = "class", action = "classdetails" } );

Action: public ActionResult classdetails(string URLName){


Anchor that invokes route:

I am getting 404 when it is clicked or I enter URL in browser.

jeudi 9 juin 2016

Upgraded MVC3 projetcs to MVC5 open in VS.Net 2015 Admin Only

I have upgraded few of our ASP.Net MVC3 applications to ASP.Net MVC5. The migration was done on Visual Studio 2015 Enterprise in Admin mode. All went successful, projects built successfully, but when same projects open in Visual Studio 2015 without Admin mode, IDE is not able to open them. Below is the error,

D:\Source\ProjA\XYZ.Web.csproj : error  : Access to the path 'D:\Source\ProjA\XYZ.Web.csproj' is denied.

 : error  : The operation could not be completed. The parameter is incorrect. 

I did check folder and files has sufficient privilege to read/write. Do anyone know what could be the reason?

passing section id in mvc using @Url.Action so that user will be scrolled to a particular section after redirecting

I am a web designer but I am told to design static pages in mvc where rather then using href="some url" I have to use href="@Url.Action("Controller", View)" Now I want to pass a section id in the url so when the user redirects it will be scrolled down to that specific section usually in html this is the syntax I use


in Html I have something Like this

<section id="mysection">


I want to Know How I am gonna do this thing in mvc. Thanks

getting error while running my mvc project .error for which i didn't use in my project

I did not use anywhere but when i compile my project then i get a compilation error.I have attached a image of error please help me why this error is occurred.i find this in my entire solution but it is not usedenter image description here

String Display in normal form in mvc Razor

i am new in mvc razor technology. i create one application in which i used html tag i.e DIV which i had given id to it.

i want to add dynamic data to that div in that but it added successfully but i display html tags.

@model Piranha.Models.PageModel
  ViewBag.Title = Model.Page.Title;
  string myData = string.Empty;
  List<Piranha.Entities.Post> posts = null;
  using (var db = new Piranha.DataContext())
    posts = db.Posts.OrderByDescending(p => p.Published).ToList();
 if (posts.Count > 0)
    foreach (var post in posts)
        myData += @Html.Raw(string.Format("<ul class=\"news - list\"><li>  <div class=\"news - wrap\"><span class=\"news - title\"><a href=\"javascript: void(0)\">{0}</a></span><span class=\"news - descr\">{1} </span></div></li>", @post.Title, @post.Description));


I Used Jquery to bind data

<script type="text/javascript">
$(document).ready(function () {

but unable to display in html for

mercredi 8 juin 2016

Can i populate specific form when a item is selected from the combobox

when i select an item from combobox, i want to populate appropriate form for user input. Is it possible? ex: if a user selects 'Address' from combo box, I want to populate form with address fields else if user selects phone, want to populate form to enter phone details...

Many Thanks VM

301 Redirect with url rewrite in web.config

Does somebody has expierience about url rewrite with rules in web.config, and how to define the match condition?

I have

And I want to rewrite

How can I define the match condition, and the action type="Redirect" (permanent 301)

Thanks for any help!

mardi 7 juin 2016

iphone take photo issue in safari showing error message

I've been searching for the solution for this error message i get in safari: "a problem occurred with this webpage, so it was reloaded"

Sometimes it works well, sometimes the message appear. it happens when i'm trying to upload using 'take photo' in safari using iphone 6 ios 9. after several times of uploading, the message will appear.

can someone know how to fix this? some said it was an intermittent issue. I don't know what is the root cause of this issue.hope someone help me.

thanks in advance.

after several upload

Web api not returning json while consuming in client

I have created a web api and i am consuming it by clinet but my web api is returning wrong format instead of JSON.

WEB API code

    public HttpResponseMessage Get()
        return base.BuildSuccessResult(HttpStatusCode.OK, todoService.GetData());

CODE for consuming web api

                        client = new HttpClient();
                        string RestUrl = "";

                        client.BaseAddress = new Uri(RestUrl);
                        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                        HttpResponseMessage response = client.GetAsync("api/TodoItems/Get").Result;
                        var content = response.Content.ReadAsStringAsync().Result;
    var uri = new Uri(string.Format(RestUrl, string.Empty));

OUTput that i am getting

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<title>Client Validation</title>
<script type="text/javascript">
function setCookie(c_name, value, expiredays) {
            document.cookie = c_name + "=" + escape(value) + ((expiredays==null) ? "" : ";expires=" + expiredays) + ";path=/";
function getHostUri() {
            var loc = document.location;
                    return loc.toString();
var exdate=new Date();
setCookie('DOAAuthReferrer', document.referrer, exdate.toUTCString());
setCookie('DOADFgsjnrSFgsg329gaFGa3ggs9434sgSGS43tsgSHSG35', '#392fc2a39a8bf6848e4f5e7551888a6d8a9db50a#FFWW#1466187439#794189797#', 'Fri, 17 Jun 2016 18:17:19 GMT');
try {  
} catch (err1) {  
    try {  
    } catch (err2) {  
        location.href = getHostUri();  
<noscript>This site requires JavaScript and Cookies to be enabled. Please change your browser settings or upgrade your browser.</noscript>

BUT i want to get json while consuming instead of above output..Please let me know what should i do???????

Issues when downloading PDF file from MVC application

I have created a function where a user can download a pdf file from my webpage. The file is stored in a databse and is requested from a webapi. The return value of the webapi is a byte[].

My issue here is that when i run the web application on my local iis this function runs without any errors. I get the pdf file and it is downloaded correctly on my machine. But when i deploy the web application to my Test server this code generates either RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION in chrome with some of the files where as other files are downloaded to the machine but when i try to open the pdf file i get: could not load the pdf file.

This happens with both chrome and IE.

This is my code:

public virtual FileResult DownloadTranslationFile(Guid id)
    Guid assessmentTemplateId = id;
    File translationFile = Services.GetFileContent(assessmentTemplateId);
    var fileName = HttpUtility.UrlPathEncode(translationFile.FileName);
    this.HttpContext.Response.Headers.Add("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
    var result = File(translationFile.FileContent.Content, System.Net.Mime.MediaTypeNames.Application.Pdf, fileName);
    return result;

I have been trying to fix this issue for 2 days now but i simply cant figure out what the issue is. Hope you guys can help. Thanks.

lundi 6 juin 2016

REGular EXp IN C#

Its my Question i want to be use 5 alphabets, and must using only one number and only one Special Characters @iam using this syntax

[RegularExpression(@"^(?=.[a-z])(?=.[A-Z])(?=.\d)(?=.[\W]){7,10}", ErrorMessage = "Use letters and Atleast 1 numeric and 1 special character Must")]

Log4net not writing logs to specified path

I am working with log for net i have below LOg4Net.config file code.But It is not writing logs to defined path .Am i doing anything wrong.Shall i miss anything??



<appender name="ErrorRollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
  <file value="C:\Temp\Logs\FileTransferService\Error.txt" />
  <appendToFile value="true" />
  <rollingStyle value="Size" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="2MB" />
  <staticLogFileName value="true" />
  <!--<threshold value="ERROR" />-->
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%message%newline" />
  <filter type="log4net.Filter.LevelRangeFilter">
    <levelMin value="ERROR"></levelMin>
    <levelMax value="FATAL"></levelMax>

  <level value="ALL" />
  <appender-ref ref="InfoRollingLogFileAppender" />
  <appender-ref ref="ErrorRollingLogFileAppender" />
  <appender-ref ref="trace" />

<!--<logger name="CustomLogger">
  <level value="ALL" />
  <appender-ref ref="InfoRollingLogFileAppender" />
  <appender-ref ref="ErrorRollingLogFileAppender" />
  <appender-ref ref="trace" />

Assembly Info Code:

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]

Output Directory :

Copy always

dimanche 5 juin 2016

Whenever use Refresh token In Web API?

I have a web API in Server, and MVC in Client.

I issues access token with 30 minutes. How to khow whenever i need refresh token ?

Execution permission cannot be acquired - FileLoadException: Could not load file or assembly 'Microsoft.VisualStudio.Web.PageInspector.Runtime

I'm trying to setup an old MVC 3 Application on my development machine and trying to make it work. I'm getting he following error. I'm not sure how to resolve this. I appreciate any help over this.

Execution permission cannot be acquired.

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.Security.Policy.PolicyException: Execution permission cannot be acquired.

Source Error: 

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace: 

[PolicyException: Execution permission cannot be acquired.]
   System.Security.CodeAccessSecurityEngine.TryResolveGrantSet(Evidence evidence, PermissionSet& grantSet) +11652088
   System.Security.CodeAccessSecurityEngine.ResolveGrantSet(Evidence evidence, Int32& specialFlags, Boolean checkExecutionPermission) +44

[FileLoadException: Could not load file or assembly 'Microsoft.VisualStudio.Web.PageInspector.Runtime, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. PolicyException thrown. (Exception from HRESULT: 0x80131416)]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +36
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
   System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark) +102
   System.Reflection.Assembly.LoadFrom(String assemblyFile) +34
   Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader.GetRuntimeAssemblyFromRegistry(Assembly& runtime) +23
   Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader.LoadRuntime() +21
   Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader.PreApplicationStart() +46

[InvalidOperationException: The pre-application start initialization method PreApplicationStart on type Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader threw an exception with the following error message: Could not load file or assembly 'Microsoft.VisualStudio.Web.PageInspector.Runtime, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. PolicyException thrown. (Exception from HRESULT: 0x80131416).]
   System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +613
   System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +141
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +102
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +157
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +531

[HttpException (0x80004005): The pre-application start initialization method PreApplicationStart on type Microsoft.VisualStudio.Web.PageInspector.Runtime.Loader.RuntimeLoader threw an exception with the following error message: Could not load file or assembly 'Microsoft.VisualStudio.Web.PageInspector.Runtime, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. PolicyException thrown. (Exception from HRESULT: 0x80131416).]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9946132
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +90
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +261

vendredi 3 juin 2016

Sql Stored proc and Entity framework 6

Suppose i have a one parameter stored procedure :

procedure dbo.MyStoredProc @param VARCHAR(50)
FROM whatever
WHERE column = @param

In my web application (mvc with entity 6) i wish to call my stored procedure, and retreive all the line from it's SELECT statement.

 var DBLines = MyStoredProc(parameterValue);

I saw something disappointing but very logic; my var was containing an integer. That integer was 1. It was telling me that everything went ok in my stored procedure...

I want that var to contains every SQL lines my stored proc went through. I suppose it is possible but how ? There must be a commun logic. All i saw on internet... was workarounds.

How to handle form post in ASP.NET MVC

i am doing a normal form post,

form action="" method="POST"

On submit, form will submit radio button value.

How do i handle this request on server side using Asp.NET MVC ?

In what form will i get the parameters (i.e query string or which other format)

how can i reset @html.Listbox to empty using jquery in MVC

@Html.ListBox("project type", new SelectList(db.tblTypes.ToList(), "ID", "Name"), new { multiple = "multiple", id = "projectType" })

jeudi 2 juin 2016

MVC 3 remote validation not firing for a date inside a Html.BeginCollectionItem block (also tried limit through jQuery datepicker with no luck)

I am trying to implement MVC 3 RemoteValidatorAttribute for the first time. But it is not firing and I don't know what I am doing wrong.

I have a Create view with the following*

@model Demo.Models.Entity
@using Demo.Models;
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
@using (Html.BeginForm("Create", "Entities", FormMethod.Post, new { enctype = "multipart/form-data", role = "form" })) 
        <tr class="editor-table-detail-row">
            <th>Purchase Date</th>
        @foreach(EntityDetail detailItem in Model.details)
            Html.RenderPartial("_DetailEditorRow", detailItem);

The partial view code is as follows*

@model Demo.Models.EntityDetail

<tr class="editor-table-detail-row">
@using (Html.BeginCollectionItem("details"))
        @Html.EditorFor(model => model.purchaseDate, "BootstrapDefaultDatePicker")
        @Html.ValidationMessageFor(model => model.purchaseDate)
        <a href="#" class="delete-table-row">Delete</a>

I create a ValidationController as follows*

using System;
using System.Web.Mvc;

namespace PostalRepairs.Controllers
    public class ValidationController : Controller
        public JsonResult ValidateDateNotFuture(DateTime date)
            if (date <= DateTime.Now) 
                return Json(true);

            return Json(false);    

And the EntityDetailClass is as follows * using System; using System.ComponentModel.DataAnnotations; using System.Collections.Generic; using System.Web.Mvc;

namespace Demo.Models
    public class EntityDetail 
        [Display(Name = "Purchase Date")]
        [Remote("ValidateDateNotFuture", "Validation", HttpMethod = "Post", ErrorMessage = "The {0} cannot be in the future.")]
        public DateTime? purchaseDate { get; set; }

*I have removed the lines not involved in the behavior I am trying to reproduce and change model, controller, view and attribute name for confidential issues. The only real names are EntityDetail.purchaseDate and all the code in ValidationController class.

But when I test the solution the purchase date is accepting invalid dates (according to business rules, purchase date should not be in the future). If a place a breakpoint inside ValidateDateNotFuture controller action method the break point never stops execution so I am guessing the action is never being called.

Can anyone give me some lights?

BTW I was trying to limit the purchase date datepicker but this jquery code is not working. If I can limit the input then the remote validator would not be necessary. I am using a bootstrap template in this project

$("#add-details-table-item").click(function () {
        url: this.href,
        cache: false,
        success: function (html) {
                maxDate: '+0'
    return false;

$("tr.editor-table-detail-row .default-date-picker").each(function () {
        maxDate: '+0'

I have tried with .datepicker({ maxDate: 0 }); .datepicker({ maxDate: '0' }); .datepicker({ maxDate: '+0' }); .datepicker({ maxDate: $.now() });

And no luck.

Reading HtmlHelper data without postback in MVC

I've added a checkbox in cshtml file like this :


In the same file i need to test if it's checked or not, I'm stuck here , any idea how can i proceed without doing a postback?


MVC @RenderBody() and RenderAction

I have a layout with one "RenderAction" and @RenderBody().

@{Html.RenderAction("View1", "Controller");}

Well, MVC first call the controller of @RenderBody() then call the controller of RenderAction. Is there any way to call the "RenderAction"'s controller first ?

Script not loading

Hi guys i am losing a lot of time on a problem that might be easy, and i bet it is a simple thing, so in the layout.cshtml i load all my scripts like this

<!DOCTYPE html>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>

    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                    <li>@Html.ActionLink("About", "About", "Home")</li>
                    <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
    <div class="container body-content">
        <hr />
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>

@RenderSection("scripts", required: false)
<script type="text/javascript" src="~/Scripts/bootstrap-filestyle.js"> </script>

the scripts that are in this page are loaded in the buldeconfig like this:

 public class BundleConfig
    // For more information on bundling, visit
    public static void RegisterBundles(BundleCollection bundles)
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(

        bundles.Add(new ScriptBundle("~/bundles/UserScripts").Include(

        bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(

        bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(

        bundles.Add(new StyleBundle("~/Content/css").Include(

a strange thing is happening i jquery code on the CrowdTouring.cs that should be aplied for 2 pages, my register and my edituser, in the register it is working it disables a button, but in my EditUser it doesnt work and i dont know why i already tryed everything :S

Here is my Jquery CrodwTouring.js

$(document).ready(function () {
$("#checky").click(function () {
    $("#RegisterBut").attr("disabled", !this.checked);

$("#TipoUtilizador").change(function () {
    if ($(this).val() == "Cliente") {
        $("#TextoTipoUtilizador").text('Crie desafios de inovação turística e obtenha melhores soluções a um preço mais acessível e de melhor qualidade');
    if ($(this).val() == "Resolvedor") {
        $("#TextoTipoUtilizador").text('Crie Soluções para os desafios e obtenha uma grande variadade de prémios');
    if ($(this).val() == "Avaliador") {
        $("#TextoTipoUtilizador").text('Avalie as soluções e ganhe notoriedade na plataforma');

$("div.myclass").hover(function () {
    $(this).css("background-color", "red")

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {


$("#ImagePath").change(function () {


Finally in my editUser page i load the scripts like that on the bottom

 <div class="form-group">
        <div class="col-md-offset-3 col-md-9">
            <input type="submit" value="Save" class="btn btn-default" />


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

@section Scripts {