lundi 29 février 2016

asp mvc Caching static contents gives 500 Internal Server Error

Our site is hosted in go daddy plesk, its been 1 day i am trying increase the performance of the site by caching static contents like css, js , images.

I am using both UseMaxAge and UseExpires in web.config and it gives good results in google speed insights 88/100 , but when i do a force refresh all images and fonts which are in different folders are not loaded , in chrome console it shows: 500 Internal Server Error for images and fonts



 <clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" 
 cacheControlMaxAge="24.00:00:00" />

 <clientCache cacheControlMode="UseExpires" 
 httpExpires="Tue, 19 Jan 2038 03:14:07 GMT" />


Action Method

private static MemoryCache _cache = MemoryCache.Default;

[OutputCache(Duration=60, VaryByParam="none")]
public ActionResult Index()

// Data Caching

if (!_cache.Contains("cachedProducts"))

CacheItemPolicy cacheItemPolicy = new CacheItemPolicy();
cacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddDays(1);

var allProducts = (from x in db.products select x).Take(20).ToList<products>();

   _cache.Add("cachedProducts", allProducts, cacheItemPolicy);

ViewBag.Products = _cache.Get("cachedProducts");

return View();


does this anything to do with app pool ? i dont have controll over IIS Manager, becuase its shared hosting.

am i doing anything wrong ?

Any help would be great.

Trying to extend a LabelFor MVC4 helper, and not being picked up... puzzled?

I am using MVC4, ASP.NET4.5, C#

I am trying to get my application to use my extended LabelFor helpers, but the original MS helpers seem to be used all of the time.

My calling code:

 @Html.LabelFor(m => m.myRecords.First().myValue)

My Helper:

 public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);

I have only added the start of the helper as I believe the issue is to do with the helper parameter signature. I am assuming if my calling signature matches my helper signature then the above helper will be used rather than the standard MS LabelFor code.

Any advice please? Thanks.

Inconsistent MVC parameter error in IE

I've got a user who is seeing an error in my MVC3 application, that I can't explain.

The exception is:

The parameters dictionary contains a null entry for parameter 'extractID' 
of non-nullable type 'System.Int32' for method 
'System.Web.Mvc.PartialViewResult SelectExtract(Int32)' ...

I understand what this exception usually means, but it shouldn't be happening here.

The method is:

public PartialViewResult SelectExtract(int extractID)

The call comes via jQuery AJAX, and works for everyone else, but not this person. I've inspected the network traffic in the browser developer tools (IE9), and as expected, it correctly contains a POST body of extractID=9.

They have hard-refreshed, so I know they're getting the most recent javascript files.

In Chrome, and in private browsing mode in IE, everything works fine for this user - or if the user wipes their IE history/cache/cookies/etc., it works. So I'm assuming there's something funky happening in IE, but I've seen this a few times with a few different users, so I can't write it off as a one-time IE glitch.

Any idea what I should be looking for?

dimanche 28 février 2016

How to make a custom pattern for regex string validation

Hi I would like to know how to write a pattern for a regex in Razor/MVC3. I have been searching how to write the pattern but since I didn't know anything about MVC/Razor I only found a regex pattern for

characters only

numbers only

character and numbers only

email address. 

Those patterns I found are not the one I am looking for. I would like to create a pattern which will exempt these characters "&';,<>. I thought of one way doing it. Like this:

^[a-zA-Z0-9_!#$%()-=~^|+and so on..]*$

Do I have to list all the characters just to exempt those? Or there is more an efficient way of doing it?

samedi 27 février 2016

Dynamic Serving for mvc

I have a website which utilizes different urls scheme for rendering content to various devices. Desktops website is at while the Mobile devices are redirected to Both are different website with same content mostly barring a url or two which render 500 error on mobile since there is no corresponding page.

Redirection Code ::

        string u = Request.ServerVariables["HTTP_USER_AGENT"];
        string path = Request.Url.PathAndQuery;
        Regex b = new Regex(@"android.+mobile|avantgo|bada\\/|blackberry|BB10|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\\/|plucker|pocket|psp|symbian|treo|up\\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino", RegexOptions.IgnoreCase | RegexOptions.Multiline);
        Regex v = new Regex(@"1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\\-(n|u)|c55\\/|capi|ccwa|cdm\\-|cell|chtm|cldc|cmd\\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\\-s|devi|dica|dmob|do(c|p)o|ds(12|\\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\\-|_)|g1 u|g560|gene|gf\\-5|g\\-mo|go(\\.w|od)|gr(ad|un)|haie|hcit|hd\\-(m|p|t)|hei\\-|hi(pt|ta)|hp( i|ip)|hs\\-c|ht(c(\\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\\-(20|go|ma)|i230|iac( |\\-|\\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\\/)|klon|kpt |kwc\\-|kyo(c|k)|le(no|xi)|lg( g|\\/(k|l|u)|50|54|e\\-|e\\/|\\-[a-w])|libw|lynx|m1\\-w|m3ga|m50\\/|ma(te|ui|xo)|mc(01|21|ca)|m\\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\\-2|po(ck|rt|se)|prox|psio|pt\\-g|qa\\-a|qc(07|12|21|32|60|\\-[2-7]|i\\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\\-|oo|p\\-)|sdk\\/|se(c(\\-|0|1)|47|mc|nd|ri)|sgh\\-|shar|sie(\\-|m)|sk\\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\\-|v\\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\\-|tdg\\-|tel(i|m)|tim\\-|t\\-mo|to(pl|sh)|ts(70|m\\-|m3|m5)|tx\\-9|up(\\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|xda(\\-|2|g)|yas\\-|your|zeto|zte\\-", RegexOptions.IgnoreCase | RegexOptions.Multiline);
        if ((b.IsMatch(u) || v.IsMatch(u.Substring(0, 4))))
            if(!path.Contains("Images") && !path.Contains("news-images"))
                string redirectTo = ""+path;

My website is getting around 3 years old but still the kind of growth one expects is nowhere and I assume this might be one of the reasons for it. Therefore I plan on using Dynamic serving with one URL. Searching on the internet I couldn't find a way how to handle this is A small demo or tutorial link to utilize this will be helpful to make the site use Dynamic Serving.

where to type command "sudo chmod 0777"

I'm using MVC. I have hosted my website on appharbor. Everything is working fine on localhost. On live website I'm getting error.

Server responded with a status of 403 (Forbidden)

enter image description here

To solve this issue. I added <modules runAllManagedModulesForAllRequests="true" /> in web.config but it didn't work.

Another solution is I need to You need to change permissions on the folder bootstrap/css. To change permission I have to type command sudo chmod 0777. But I cannot figure out where to type this command.

So where I have to type this command or what is the alternative to tackle this 403 issue.

how to prevent deault Alt+S in firefox

I am Using jquery in my mvc project .i am creating keyboard shortcut for saving,cancelling ,Add new for that i am using Alt+S,Alt+C,Alt+S,its working on chrome,on firefox ,its Alt+S is not working .

i am using these codes-

$(document).on('keydown', function (e) {

// e.preventDefault();

e.preventDefault ? e.preventDefault() : event.returnValue = false;

var key = e.which || e.keyCode;

if (e.altKey === true && key === 78) {-Colling a Add Function

    //  AddCompany(); -i adding a new company

    alert('Are You Want to Add New Company ');

if (e.altKey === true && key === 83) {-Colling a save Function

    // funSaveCreation();- save function

    alert('Are You Want to Save Company ');

if (e.altKey === true && key === 67) {--Colling a cancel Function

    // Cancel();- cancel function

    alert('Are You Want to Cancel ');


vendredi 26 février 2016

How to display an mvc view as popup modal from an aspx page which will communicate with the controller

I am loading an mvc view from a link in an aspx page using the following code. The problem is that the view is unable to communicate with the controller. Is there an alternate way to show a view in a modal popup which will communicate with the controller for retrieving and saving data from the displayed page?

      $(function () {
          $('body').on('click', '.draw-edit-Link', function (e) {

              $.get(this.href, function (html) {
                  $('<div />').kendoWindow({
                      visible: true,
                      title: 'My Documents',
                      modal: true,
                      width: '1200px',
                      deactivate: function () {

   <a id="drawEdit" class="draw-edit-Link" href="/MySite/Purchase/MyDocument>My Document</a>

Upgrade from ASP.NET MVC 3 with ASP view engine to MVC 5

Can I upgrade my project having ASP.NET MVC3.0(visual studio 2010) using ASP view engine into ASP.NET MVC5.0 Visual Studio 2013.

jeudi 25 février 2016

The conversion of a datetime2 data type to a datetime data type issue even if dates are correct

I am getting an error of

"The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value"

while saving my data even if my dates are correct. My dates are not too old.
but still I am getting this error.

Please refer screenshot Image

how to add style in Dropdownlistfor helper in mvc?

Want to add style with onchange function in dropdownlist my code is something like this :-

 @Html.DropDownListFor(m=>m.printEmployeeCardDTO.DataCardConnectionType,null,new {    @onchange="_printEmployeeCard.GetPrintersDetail(this.value, printersList);" },new    { style = "width: 100px;" }  )

I m getting error in this. Could anyone help me in it?

Mvc string encoding inside tag attribute

I have specific url for href attribute: $httpUrl('Get-Id','id','V4GX')$". The whole html looks the following way:

<a class="link" href="@MvcHtmlString.Create("$httpUrl('Get-Id','id','V4GX')")">TEST</a>

So I assume that string inside of href attribute won't be encoded. However after rendering the page I get the following result:

<a class="linkl" href="$httpUrl(&#39;Get-Id&#39;,&#39;id&#39;,&#39;V4GX&#39;)$">TEST</a>

@Html.Raw("$httpUrl('Get-Id','id','V4GX')") returns the same result

Finally, I have found the workaround:

<a class="link" @Html.Raw("href=\"" + @MvcHtmlString.Create("$httpUrl('Get-Id','id','V4GX')") + "\"")>TEST</a>

However it doesn't look very well. So the question is: Why MvcHtmlString or Html.Raw is getting encoded anyway inside of html attribute?

Comaprison of two integers fields in view model on post

I have two fields in my view model

 public decimal Rate { get; set; }
 public decimal GrossRate { get; set; }

Gross rate should be greater than or equal to Rate. validate that whether gross rate is equal or greater than rate if gross rate enter is less it will display error there is something possible that i can validate from view model. i dont want to use if statement on postback.

mercredi 24 février 2016

VS2012 How to add external javascript to packages.config

I'm new to the concept of packages.config and NuGet so feel free to correct me if my understanding is off. I created a new web project in VS2012 and I saw that packages.config was there to manage the javascript files. I used the NuGet package manager to add the metro ui package and it added version 2.0

However, the latest version is 3.0 and that's the one I would like to use. I tried deleting 2.0, replacing it with 3.0 and updated the package.config file with the corresponding verision number. But every time I open the project, it tries to override the file with version 2.0

My question is what is the proper approach update a package in which, the NuGet package manager doesn't hold the latest version?

Chech whether the USER is authenticated/not while trying to browse using direct URL

Thanks in advance. I want to restrict users based on their authorization to my application while they are trying to access URL directly in browser. We are getting the flags from Database table whether the user has access to perticular services or not. We are having n number of controllers, so I can't use session variables. Can you please suggest that how can I use those flags to restrict users by custom actionfilters.

Wrapping entire method in try/catch vs specific lines?

I'm getting an exception a large method. It's a null reference error. I'm going to add some additional exception handling and logging to this method.

Will I get better exception details if I wrap the entire inner method code in one large try/catch? Or will it produce the same outcome?

The current exception points to the closing brace of this large method.

mardi 23 février 2016

Ajax Call from JS to Controller is too slow

I using the MVC Application and i am calling controller through ajax call after loading the page.but when i am calling method from controller through ajax it taking more than 4 mins to hit the controller breakpoint, can any one tell what is the problem

Asp.Net MVC Call Repetitive C# Code of Layout Page on Server

I am using Asp.Net MVC 5. I have some code of C# which I have to call on layout page every time it loads. I want to keep this code on server and then get the data through ViewBag as to lessen page load. Any help?

Get Logged In User (Current User's)'s Information

I have user information stored like this in my table:

ID(PK) |  Email     | Pass | DepartmentID
 1    hash    301
 2   hash    302
 3   hash    303

Now , I need to get current user's (logged in user's ) Department ID via a jQuery getJson Call from the view side but cannot find any suitable approach to do so.

My Script(snippet) in view is something like :

   var url="@Url.Action("Details","Users")";
    $.getJSON(url, function(data){



And My code in controller (snippet) is:

public ActionResult Details()
    var user = User.Identity.Name;
    return Json(user, JsonRequestBehavior.AllowGet);

Please help with an appropriate method.
Thank You.

DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'col_SortOrder'

aspx page:-

<ASP:TemplateColumn HeaderText="SortOrder" SortExpression="col_SortOrder">
                                <ASP:Label ID="lblSortOrder" Runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.col_SortOrder","") %>'>
                            <FooterStyle HorizontalAlign="Center"></FooterStyle>
                                <asp:TextBox MaxLength="20" ID="txtSortOrderF" Runat="server" Text=""></asp:TextBox>
                                <asp:TextBox MaxLength="20" ID="txtSortOrderE" Runat="server" Text='<%# DataBinder.Eval(Container, "DataItem.col_SortOrder","") %>'>

aspx.cs page

   private DataView GetPizzaItems()
                DataSet ds = null;
                string strQuery = "Select * From tbl_Pizzas";
                ds = clsADO.getQueryResults(strQuery);

                if ((ds != null) && (ds.Tables.Count > 0))
                    DataView dv = ds.Tables[0].DefaultView;
                    if (ViewState["SortOrder"] != null)
                        dv.Sort = ViewState["SortOrder"].ToString();
                    return dv;
                    return null;
            catch (Exception ex)
                throw ex;

        private void Rebuild_Display()
                this.dgPizza.DataSource = GetPizzaItems();
            catch (Exception ex)
                throw ex;

public List<tbl_Pizza> GetPizzas()
            var list = from a in db.tbl_Pizzas
                       select a;
            return list.ToList();

Trying to retrieve data from table but it is showing error as does not contain a property with the name col_SortOrder, but i declared the col name in table,can any one please help me out DataBinding: 'System.Data.DataRowView' does not contain a property with the name 'col_SortOrder'.

lundi 22 février 2016

ASP.NET MVC : repository classes


  1. Services
  2. Content
  3. ContentData
  4. Subscriptions

Things needed need to make 4 pages, CRUD


  1. Entity Framework Code First Required
  2. Cant use Migrations of Entity Framework (ie create table from database not from EF)
  3. Create Separate database: SMS_yourname
  4. 4 projects required => Infrastructure, Repository, Model, WebMVC (.NET framework 4.0)
  5. Repository classes should have only constructor and FindAll method no other methods are allowed, cant have FindAll method in ContentRepository
  6. Controller should have only constructor no other methods are allowed
  7. Can't use custom extension method
  8. JavaScript files => jquery, jqueryui, validation engine, bootstrap 3
  9. Use AutoFac for IoC
  10. Cant use new keyword to create classes for repository

I really have no idea where am I suppose to write Add, update, delete functions with the given conditions. Please help me out.

Foreign key of ApplicationUser and Controllers

I got a similar problem. After making the relations in my model, I got a error in the Controller (Create and Edit). I tried some things, but nothing seems to resolve the problem. Any ideas? Thanks!


public class JbsTest{

public int Id { get; set; }
public string Description { get; set; }
public double Duration { get; set; }

public int ProjectId { get; set; }
public virtual Project Project { get; set; }

public string UserId { get; set; }
public virtual ApplicationUser User { get; set; }


public ActionResult Create()
    ViewBag.ProjectId = new SelectList(db.Projects, "Id", "Name");
    ViewBag.UserId = new SelectList(*db.ApplicationUsers*, "Id", "Name");
    return View();

This line shows the error:

ViewBag.UserId = new SelectList(*db.ApplicationUsers*, "Id", "Name");

ApplicationDbContext class:

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)

    public static ApplicationDbContext Create()
        return new ApplicationDbContext();

    public System.Data.Entity.DbSet<TestProject5.Models.JbsTest> JbsTests { get; set; }

Error Msg: enter image description here

.NET MVC3 How do I get a link to a view to render the CSS?

My stylesheets are properly referenced in the header, and render the CSS for the views properly when going through the controller, e.g:

<link rel="stylesheet" href="Content/style/ddlevelsmenu-base.css">
<link rel="stylesheet" href="Content/style/ddlevelsmenu-topbar.css">

But when I create a hyperlink in my menu like this:

<a href="home/index" class="blightblue"> <i class="icon-home"></i> Home</a>

It opens the page fine, but does not render the CSS.

I tried adding

@RenderSection("styles", false);

to my Index view, but it blew up.

I am using Visual Studio 2012 and MVC 3.

Drop Down List select 1st index value by default(id 1) either i select other values

I have 4 values in drop down list(1,2,3,4) either i select id(2 or 3 or 4) but the value entered in Database is id(1)


dimanche 21 février 2016

Checkbox data persists

I have a drop down list and on clicking on the drop down list , a grid comes up with checkbox .i select a row by clicking on the checkbox but i dnt perform any further action , i again select other option from downdowlist and dont perform any action. i go back to the first option in drop dropdownlist and the old data comes up. now without clicking on any checkbox i put click the submit button. the action gets completed on the previously selected checkbox WHICH IS WRONG. please help me out as i dont want this to happen .

Binding ASP.NET MVC 3 model to Knockout view model

I'm trying to integrate my ASP.NET MVC 3 model with Knockout, but it requires a lot of manipulation and I'm trying to avoid that. Could my solution be rewritten to something smarter using i.e. Knockout Mapping?

I have a view where i bind my MVC model programmatically to a Knockout view model. Two checkbox inputs are parameters to an AJAX call whose response is supposed to populate my data table. I serialize my MVC model, create observables from the serialization data, translate the data to PascalCase when the user clicks the button, camelCase the response data and push it in to my observable array.

I have two view models in C#:

namespace Vikekh.BindingMvcToKnockout.ViewModels
    public class SearchViewModel
        public IEnumerable<ItemViewModel> Items { get; set; }
        public bool ShowTypeA { get; set; }
        public bool ShowTypeB { get; set; }

    public class ItemViewModel
        public int Id { get; set; }
        public string Name { get; set; }
        public string Type { get; set; }

In my view I have:

<input type="checkbox" data-bind="checked: showTypeA"> Show Type A
<input type="checkbox" data-bind="checked: showTypeB"> Show Type B
<button data-bind="click: load">Refresh</button>
    <tbody data-bind="foreach: items">
        <td data-bind="text: name"></td>
        <td data-bind="text: type"></td>
$(function () {
    function ViewModel(data) {
        var self = this;

        // translate from C# to KO model
        self.items = ko.observableArray(data.Items);
        self.showTypeA = ko.observable(data.ShowTypeA);
        self.showTypeB = ko.observable(data.ShowTypeB);

        self.load = function () {
            // translate from KO to C# model
            var data = {
                ShowTypeA: self.showTypeA(),
                ShowTypeB: self.showTypeB()

            $.post($.url('Items/Load'), data, null, 'json').done(function (data) {

                if (data && data.length > 0) {
                    for (var i = 0; i < data.length; i++) {
                        self.items.push(new Item(data[i]));

    function Item(data) {
        var self = this;

        // translate from C# to KO model = data.Id; = data.Name;
        self.type = data.Type;

    var jsonModel = '<%= Html.Raw(JsonConvert.SerializeObject(Model)) %>';
    var mvcModel = ko.mapping.fromJSON(jsonModel);
    var data = ko.mapping.toJS(mvcModel);
    var viewModel = new ViewModel(data);


But there must be a more sophisticated way to do all this binding? I've created a JSFiddle which mocks the C# implementation. Please, do look and see if you can better it!

Set Text Box value using drop-down list's selected value

I have a schema ( table saved in Sql) like this:

 ID | Name | Address
 1     Sam     ADD1
 2     John    ADD2
 3     Tony    ADD3

I have three fields in my form - ID , Name and Address.
Now I have implemented a drop-down for the ID field using ViewBag to pass data between the view and the controller.
I want to set the value of the fields Name and Address using the ID selected from the drop-down and not manually but I am unable to figure out a way and tried searching but could not find any appropriate solution.
Thanks for the Help.

show sign out button after successfull login

I am using mvc3 application where after click on login button i am checking that user is validated or not using ajax call in jquery. If user is authenticated then i return true and in Onsuccess method i am redirecting it to home page. Below is the code:

function OnSuccess(response) {
    var mesg = $("#lblMess")[0];
    switch (response) {
        case true:
            var url = "/Home/Search";
            $(location).attr('href', url);
        case false:
   = "red";
            mesg.innerHTML = "Email id or Password is incorrect";
        case "error":
   = "red";
            mesg.innerHTML = "Error occured";

Till here working fine. Now i added one signout button in _layout.cshtml page which i made visibility none in login page, so if i show this signout button before switch starts and user is not valid then signout button displays but if user is authenticated and trying to show signout button inside true case then it is not working. Need help.

vendredi 19 février 2016

How to migrate VS2010 MVC3 project to VS2015?

When I try to open an existing solution (to ultimately convert it to later MVC and .NET packages), VS2015 rejects the project:

The application which this project type is based on was not found. Please try this link for further information:

That link is worthless as it takes me to a VS2013 compatibility page.

My goal is to migrate the project from MVC3/.NET4.0 to MVC5/.NET4.5.

I can't target a later MVC or .NET in VS2010. VS2015 won't open the older project so the solution here won't work Some (official or not) upgrade Mvc3 to Mvc5 guide?? for changing the properties of the project since the project won't open.

Override EditorTemplate based on BeginForm

I am using EditorTemplates to style all my input fields. Works like a charm, however now I want two themes of EditorTemplates, one for normal forms, and then one for my wizard forms.

I am already using an overloaded Html.BeginWizardForm() around those Html.EditorFor - but how do I make the MVC logic react on being inside Html.BeginWizardForm() ?

Get the duration of video in mvc

i needed the duration of video from physical path code which i have tried

using WMPLib;
WindowsMediaPlayer wmp = new WindowsMediaPlayerClass();
IWMPMedia mediaInfo = wmp.newMedia(Server.MapPath("~/Uploads/test.mp4"));
double duration = mediaInfo.duration;

but i am getting following error The type 'WMPLib.WindowsMediaPlayerClass' has no constructors defined Interop type 'WMPLib.WindowsMediaPlayerClass' cannot be embedded.

jeudi 18 février 2016

Pass Array to Controller From View Without Using Ajax

I am Using mvc 5. I want to pass array of string from view to controller without using Ajax. Can Anyone help?

Drop down list not showing as required but is marked as required

I have an issue with dropdown list with MVC. but there is no issue with textboxes, only with dropdown lists. I want to first say that I spent an extensive time on that and still no solution. I also want to mention that the properties are marked with [Required] attribute. In the view, I also have jquery.min, jquery.validate.min, jquery.validate.unobstrusive.min. I also have :

<add key="ClientValidationEnabled" value="true"> 
<add key="UnobtrusiveJavaScriptEnabled" value="true"> 

ViewModel Code:

public class RegistrationViewModel
    [Required(ErrorMessage = "State is required.")]
    public IEnumerable<SelectListItem> State { get; set; }

in the view:

    @Html.DropDownListFor(model => model.StateSelectedItem, (List<SelectListItem>)Model.State)
    @Html.ValidationMessageFor(model => model.State)

Any idea, thoughts, comment? Thanks.

Cannot Read Property of Dynamically Created Checkbox after DOM is Loaded

I have an application that allows users to select one or more courses. The user may choose to save the selected courses and come back later to finish the process. When/if the user returns, I recreate the list of checkboxes. Then, I try to find all the input checkboxes within that div. I log it to the console, and it returns an empty collection. How do I obtain the checkboxes properties?

The empty div that is populated with the checkboxes.

 <div class="courseList applyBackgroundColor" id="UserCheckList">


Where I am doing the post and creating the dynamic textboxes using the result.

var createCourse = function(studentID)
  var StudentCourseList = '<table><tbody>';
   do post here

 $.each(result, function (index, item) {
     StudentCourseList  += '<td valign="top" style="width:1%"' +  
     item.ID + '><div class=""><input type="checkbox" class="checkbox"  
     id="'+ item.ID + '" value="' + item.ID + '" /></div></td>
    <td valign="top" style="width:30%;padding:.25em;" id="' + item.ID +
     '"><span id="span.' + item.ID + '" title="' + item.Description + '">' 
     + item.Description             +'</span></td>';


   $('#UserCheckList').html(StudentCourseList );

Checking if there is a student id when the page loads.

  var studentID = $('#studentID').val(); 
  if(studentID !==''){
    var listCheckUsers = $('.courseList').find('input[type=checkbox]');

if I put a breakpoint next to listCheckUsers and debug it, the result that is displayed in the console is shown below:

      Object[input#MAC201.checkbox attribute value = "MATH 201",   
      input#ENC101.checkbox attribute value = "ENGLISH 101",....]

without the breakpoint, I see an empty object


Search data between dates and status of the task in [on hold]

I am making a task management system. In it I want to search specific task, search with date and status of task. Using text box for date and using drop-down for status (pending,working,complete) I want both limitation works and give authentic result.

Intellisens don't detect class

I'm going to add some Products from a list into the OrderRows table, but when I start typing db. ??? Intellisens don't give med any option to select the OrderRows class and then continue with Add.... What have I done wrong?

 var listShoppingCart = Session["ShoppingCart"] as List<Products>; // Cast

        foreach (var item in listShoppingCart)
            var productFromList = new OrderRows
                ProductID = item.ID,
                OrderID = orderId,
                Price = item.Price

            //db. ????
            //db. ?? .Add(productFromList);

These are the classes, perhaps there are some error in their relation?

    public class Orders
    public int ID { get; set; }
    public DateTime Orderdate { get; set; }
    public int CustomersID { get; set; } 

    public virtual Customers Customers { get; set; } 
    public virtual ICollection<OrderRows> OrderRows { get; set; }

    public class OrderRows
    public int ID { get; set; }
    public int ProductID { get; set; }
    public int OrderID { get; set; }
    public float Price { get; set; }

    public virtual Orders Orders { get; set; }

Javascript not recognizing controller

I am having issues with code that have worked before but now is not working. The issue is i am calling a Controller called GetRooms from my cshtml class but i am getting a 404 error.


public virtual ActionResult GetRooms(Guid unitId, Guid interviewId, DateTime date, DateTime startTime, DateTime endTime)


In my cshtml class i have implemented a getJSON requst with the paramesters:

function getRoomsInUnit(unitId, interviewId, date, startTime, endTime) {
$.getJSON('/CitizenMentor/GetRooms', { unitId: unitId, interviewId: interviewId, date: date, startTime: startTime, endTime: endTime }, function (result) {
    var list = $('#SelectedRoomResourceId');

    $(result).each(function (index, room) {
        list.append('<option value="' + room.Id + '">' + room.Title + '</option>');


When i run the code i am getting a 404 error stating that a controller with the parameters cannot be found. I cant seem to find out why this is happening. Maybe its the timestamp that is sent with my query?? enter image description here

mardi 16 février 2016

Cannot convert int to bool when upgrading from mvc3 to mvc5

I have a project in which I had upgraded from MVC3 and whatever .net version it used ( i assume 4.0 )

What I am confused about is how this code EVER worked in .net 4.0

Well, to be honest, I did have to use Telerik JustDecompile to get the source code as someone did not put changes back into TFS.....

So this Method was part of the code base in HomeController.cs

public string RasCheck(bool? val)
        bool? nullable = val;
        return ((!nullable.GetValueOrDefault() ? 0 : (int)nullable.HasValue) == 0 ? "No" : "<b>Yes</b>");

Even with C# from the .net 4.0 framework I don't see how this would have worked.


Cannot convert type bool to int

What is the best way to handle this? I'm really not found of this developer coding logic style, It just looks confusing as to what he is even trying to do, doesn't it?

Pass userId from WebUI to DAL using Ninject

I have a 3 layer application : WebUI, BLL and DAL. I need to pass UserId to DAL from WebUI layer using Ninject. Composition root is in WebUI layer. WebUI depend on BBL and BLL depends on DAL.

So question is how can I pass userId from WebUI to BLL and then to DAL. When the user is authenticated i need to pass UserId, if not authenticated - pass null.

In composition root (WebUI)

 private static void RegisterServices(IKernel kernel)

In BLL :

  public class ServiceModule : NinjectModule
        public override void Load()


public class CTO_Facade : ICTOFacade
        private ISingleEntityRepository<CargoTransportationOrderModel> _ctoRepoSingle;
        private IMultipleEntitiesRepository<CargoTransportationOrderModel> _ctoRepoMultiple;

    public CTO_Facade(ISingleEntityRepository<CargoTransportationOrderModel> singleRepo,
        IMultipleEntitiesRepository<CargoTransportationOrderModel> multipleRepo)


 public sealed class GenericRepository<T> : ISingleEntityRepository<T>, IMultipleEntitiesRepository<T> where T : BaseModel
        private string _userId;

        #region Helpers

        public GenericRepository(string userId)
            _userId = userId;

lundi 15 février 2016

CSCA37D.tmp is not a valid Win32 resource file

I am using visual studio 2010 and MVC 3. I am getting below error while building the project 'CSCA37D.tmp is not a valid Win32 resource file'. I tried solution mentioned at link - ***.tmp is not a valid win32 resource file. How to resolve this weird bug on Visual Studio? but didn't get the resolution. I tried some other solutions shared on net but non of them worked.

Please help me resolve this issue as I am facing it for couple of days now.

Photo sphere image upload validation

I'm trying to make my photo sphere gallery with MVC C#. Is there any way to test an image that is a real sphere image? A library or something? I'm currently having an upload button and I save the image's path in the Database. But I would like to validate the image that it is a real sphere image. I was searching for hours but no luck...
Thank you!

Customized Identity , Roles are not getting fetched?

I am not able to see roles when I executes this , though its there in db ?

IList<string> roles = await _userManager.GetRolesAsync(Convert.ToInt32(user.Id));

I have logged database calls for this , and its been observed that query is correct but its not using userid in where clause

Opened connection at xx PM +05:30
    [Extent1].[RoleId] AS [RoleId], 
    [Extent1].[Description] AS [Description], 
    [Extent1].[IsActive] AS [IsActive], 
    [Extent1].[CreatedBy] AS [CreatedBy], 
    [Extent1].[CreatedDate] AS [CreatedDate], 
    [Extent1].[UpdatedBy] AS [UpdatedBy], 
    [Extent1].[UpdatedDate] AS [UpdatedDate], 
    [Extent1].[DeletedBy] AS [DeletedBy], 
    [Extent1].[DeletedDate] AS [DeletedDate], 
    [Extent1].[IsSuperAdminRole] AS [IsSuperAdminRole], 
    [Extent1].[RoleName] AS [RoleName]
    FROM [dbo].[_TestRoleMaster] AS [Extent1]
-- Executing at xx PM +05:30
-- Completed in 2 ms with result: SqlDataReader

I am not understanding what I am doing wrong here.

for more details on classes how I customized ,

public class ApplicationUserRole: IdentityUserRole<int>

        public bool IsActive { get; set; }
        public bool IsDefault { get; set; }

        public int CreatedBy { get; set; }
        public DateTime CreatedDate { get; set; }

        public int? UpdatedBy { get; set; }
        public DateTime? UpdatedDate { get; set; }

        public int? DeletedBy { get; set; }
        public DateTime? DeletedDate { get; set; }



 public class ApplicationRole : IdentityRole<int,ApplicationUserRole>
        public string Description { get; set; }
        public bool IsActive { get; set; }
        public int CreatedBy { get; set; }
        public DateTime CreatedDate { get; set; }
        public int? UpdatedBy { get; set; }
        public DateTime? UpdatedDate { get; set; }
        public int? DeletedBy { get; set; }
        public DateTime? DeletedDate { get; set; }
        public bool? IsSuperAdminRole { get; set; }

dimanche 14 février 2016

best way to get fields from dynamic form - ASP.NET MVC

I have some table to create dynamic firld in Register form . I Use belows Tables:

 public class Field
    public Guid Id { get; set; }
    public string Title { get; set; }
    public FieldType FieldTypeId { get; set; }
    public string FileExtensions { get; set; }
    public ICollection<FieldItem> Items { get; set; }
    public virtual ICollection<UserField> UserFields { get; set; }
public class FieldItem
    public Guid Id { get; set; }
    public string Title { get; set; }
    public virtual Guid FieldId { get; set; }
    public virtual ICollection<UserField> UserFields { get; set; }


and I use a UserField to save data in database according to use like :

  public  class UserField
    public Guid Id { get; set; }

    public User.User User { get; set; }
    public Field Field { get; set; }
    public FieldItem FieldItem { get; set; }
    public string Value { get; set; }

My Register form has a viewModel RegisterUserViewModel and I get it in post Action Method like :

   [HttpPost, ValidateAntiForgeryToken, ValidateCaptcha]
    public virtual ActionResult Register(RegisterUserViewModel registerViewModel)

@model CMS.ViewModel.User.RegisterUserViewModel

and generate form like :

  @foreach (var item in fields)
        <div class="row">
            <div class="col-lg-3"><label>@item.Title</label></div>
            <div class="col-lg-5">
                @switch (item.FieldTypeId)
                    case FieldType.Checkbox:
                      <input type="checkbox" />
                    case FieldType.File:
                        <input type="file" maxlength="@item.MaxFileSizeLength" />
                    case FieldType.Radio:
                        foreach (var fieldItem in item.Items)
                            <input type="radio" name="@item.Title" /> @fieldItem.Title
                    case FieldType.Text:
                    <input type="text" class="form-control" />
                    case FieldType.Dropdown:
                    <select name="@item.Title">
                        @foreach (var fieldItem in item.Items)
                            <option value="@fieldItem.Id">@fieldItem.Title</option>
            <div class="col-lg-4"></div>

I have a best way to get Aall data , I know can get data by ajax and Form.Request but I want a way to bind auto or another way ?

I seached On google but cant found a similar question .

samedi 13 février 2016

Delete multiple records from a List of Id's using Entity Framework

I need to delete multiple Ids from a List of Ids.

public IHttpActionResult Delete(List<string> IDs)

But RemoveRange does not allow multiple ids , it expect only List<entities>.

Yes, I know that , if I send list of entities to server instead of sending List of ids , Then I can easily accomplish this. But I don't like that.

Again, I don't want to use foreach loop to loop through every Ids.

how make this opperation (+=) in time span in mvc

This code returns me an error and I want to make this operation:

foreach (var item in db.Panchers)
    string x = "00:00:00";
    TimeSpan zero = TimeSpan.Parse(x);
    item.AllDate = zero;
    foreach (var items in db.Times.Where(items => items.Name == item.Pancher1))
        TimeSpan span += items.All.Value;
        decimal m = Convert.ToDecimal((item.AllDate).Value.TotalMinutes);
        decimal h = m / 60;

My error is in the line TimeSpan span += items.All.Value.

jeudi 11 février 2016

BeginCollectionItem inside foreach MVC3

I have a List of view model and i try to put in 2 different view like


 @model List<SchoolApp.ViewModels.FeesModel.ScheduleTerm>
 @foreach(var item in Model)
    Html.RenderPartial("_ScheduleTerm", item);

and on view2

@model SchoolApp.ViewModels.FeesModel.ScheduleTerm
  <tr class="newtermRow">   
 @using (Html.BeginCollectionItem("ScheduleTerms"))
       @Html.HiddenFor(model => Model.TermId)
      @Html.TextBoxFor(model => Model.Term)
      @Html.ValidationMessageFor(model => model.Term)
        @Html.TextBoxFor(model => Model.DueDate, new { @class = "datepicker form-control" })
        @Html.ValidationMessageFor(model => model.DueDate)

Now on the POST event i am getting all values in the collection

But when i try to make it in single view like

 @model List<SchoolApp.ViewModels.FeesModel.ScheduleTerm>
 @foreach(var item in Model)
   <tr class="newtermRow">   
     @using (Html.BeginCollectionItem("ScheduleTerms"))
           @Html.HiddenFor(model => item.TermId)
          @Html.TextBoxFor(model => item.Term)
          @Html.ValidationMessageFor(model => item.Term)
            @Html.TextBoxFor(model => item.DueDate, new { @class = "datepicker form-control" })
            @Html.ValidationMessageFor(model => item.DueDate)

ANd on POST event List is not null but the properties in List is NULL

How can i make BeginCollectionItem works on single View within a foreach or is any limitation for BeginCollectionItem to compatible within foreach

Order the Field when Display on view in mvc

I am Display Data but field is dynamic order that it changed every time when iTs Display.


No Name  Mobile
1 Ajay 777777777
2 Vijay 8888888888
3 Sanjay 888888888

now i use reorder the field by multiselect dropdown that reorder the field problem is that if i want to display data of reorder field. how it possible.

My code

@foreach (var invoice in Model.InvoiceList)
                <td> @invoice.No         </td>
                <td> @invoice.Name           </td>
                <td> @invoice.Mobile          </td>


Its display field data only if i write manualy in view site. but if i select order

Name, Mobile, No or

Mobile,Name,No or


then how it's possible to display?

How to insert a space at a specific index in a Html.TextBox as the user types

@using (Html.BeginCollectionItem("item"))
    <td class="tdNumber">
        @Html.TextBox("Number", Model.Number, new { id = "Number", @class = "txtNumber" })

I have the above markup in an MVC3 partial view and i'm using it to dynamically add rows to a table in my main view like below on the click of a button.

How can i ensure that the number entered in this particular column for all dynamically added rows is in the format Phkn xyz nwbnyn (4 characters [space], 3 characters [space], 6 charactors)

@if (Model.FullReport.Count > 0)
    foreach (var item in Model.FullReport)
    @Html.Partial("ReportPartial", item);
    @Html.Partial("ReportPartial", Model.FullReport);

mercredi 10 février 2016

Archive counter increasing every time I publish a blog post

Every time I publish a blog post, the archive counter sees that as a new item to archive.

I think this might be a bigger problem though. If I have an existing blog post and want to make changes, pressing "save" does not save the changes. I have to go and actually publish the post again. Is there a way around this? Is there something I'm not doing in the content type definition?

Thanks in advance.

User never authenticated in MVC application

I deployed an ASP.NET MVC application on a Windows Server 2008 R2 server. I have the following action in my controller. For some reason the value of User.Identity.IsAuthenticated is always false. When I run it on my local dev machine, it works fine. My application pool identity is set to ApplicationPoolIdentity in IIS8. I went to my app folder and gave permissions to my application pool. Is there something I'm missing?

        public ActionResult Connexion()
        if (User.Identity.IsAuthenticated)
            return RedirectToAction("Index", "Accueil");

        return View();

ASP.NET MVC Redirect Partial View Request If it is not from a View

I have some partial views and corresponding action methods in a controller. I call them using Html.Action("PartialView") helper in some Views. This works fine.

However when i type the url of the action of the partial view into the address bar of my browser, controller sends me the partial view back alone(without any wrapping view or layout). This seems weird. I want my controller to redirect request of actions returning partial view to index action but not Html.Action() helpers

How can i do that?

WebAPI Put returns HTTPResponse null

I have a requirement to implement simple edit functionality.I am using webapi service to update my test object. I am calling the below method from the controller post request.

This is the controller which calls a metod in test calls wich inturn calls the put service

public ActionResult TestEdit(Test test)
            if (ModelState.IsValid)
               **objtest = TestDatabaseService.TestEdit(test.testID, test);** // this method is defined in the below class

                **if (objtest == null) // This comes null
Method which calls put service
**public HttpResponseMessage TestEdit(int id, Test test)**
            string uri = baseUri + "Test/" + id;
            using (HttpClient httpClient = new HttpClient())

                Task<HttpResponseMessage> response = httpClient.PutAsJsonAsync<Test>(uri, test);

                     return JsonConvert.DeserializeObjectAsync<HttpResponseMessage>(response.Result.Content.ReadAsStringAsync().Result).Result;
    My webapi service put method 
   public HttpResponseMessage PutTest(int id, Test test)
            if (ModelState.IsValid && id == test).testID)
                db.Entry(test)).State = EntityState.Modified;

                catch (DbUpdateConcurrencyException)
                    return Request.CreateResponse(HttpStatusCode.NotFound); 

                return Request.CreateResponse(HttpStatusCode.OK); // hree the status code is set to indicate the save is success
                return Request.CreateResponse(HttpStatusCode.BadRequest); //if asve failed

here the problem is httpresponsemessage (objtest in the first method)always return null and hence i am not able to check the status. I think i am doing some mistake in the service.

Connection Request Timed out issue again come after increase Max Pool Size

I am using and oracle DB

  • I have running online application.Minimum 100 user daily login my application.Daily 2 are 3 times come connection request timed out issue.then restart IIS solve this problem.
  • I increased Max Pool Size=9999.Min Pool Size =1;But no use increase Max Pool Size.after connection open ,properly dispose all connection in my code

Any other reason for come connection request timed out issue?

Execute stored procedure in mvc through EnterpriseLibrary

I am tyring to develop a sample project in mvc. In this, i tried to get the userlist from database (mysql). i am using enterprise library dll to set the database connectivity.

 public IEnumerable<UserViewModel> GetUserList()
        DatabaseProviderFactory factory = new DatabaseProviderFactory();
        Database db = factory.Create("MySqlConnection");
        DbCommand dbc = db.GetStoredProcCommand("uspGetUserList");
        dbc.CommandType = CommandType.StoredProcedure;

        return db.ExecuteDataSet(dbc);

i know the executedataset is to execute only dataset type... i want the command that execute IEnumerable type..... thank you

mardi 9 février 2016

MVC3 and WebApi Error Handling

I am editing an old project which is using MVC3. It has a Global.asax file which handles errors like this:

protected void Application_Error(object sender, EventArgs e)
    var currentController = " ";
    var currentAction = " ";
    var currentRouteData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(Context));

    if (currentRouteData != null)
        if (currentRouteData.Values["controller"] != null && !String.IsNullOrEmpty(currentRouteData.Values["controller"].ToString()))
            currentController = currentRouteData.Values["controller"].ToString();

        if (currentRouteData.Values["action"] != null && !String.IsNullOrEmpty(currentRouteData.Values["action"].ToString()))
            currentAction = currentRouteData.Values["action"].ToString();

    var ex = Server.GetLastError();
    var controller = new ErrorController();
    var routeData = new RouteData();
    var action = "Index";

    var code = (ex is HttpException) ? (ex as HttpException).GetHttpCode() : 500;

    switch (code)
        case 400:
            action = "BadRequest";
        case 401:
            action = "Unauthorized";
        case 403:
            action = "Forbidden";
        case 404:
            action = "NotFound";
        case 500:
            action = "InternalServerError";
            action = "Index";

    Response.StatusCode = code;
    Response.TrySkipIisCustomErrors = true;

    routeData.Values["controller"] = "Error";
    routeData.Values["action"] = action;

    controller.ViewData.Model = new HandleErrorInfo(ex, currentController, currentAction);
    ((IController)controller).Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

This works fine when there is an error inside my MVC project. There is also a base class which makes calls to an external API like this:

/// <summary>
/// Used to make a Get request to a specified url
/// </summary>
/// <param name="url">The target url</param>
/// <returns>Returns a string</returns>
public async Task<string> MakeApiCall(string url)
    return await MakeApiCall(url, HttpMethod.GET, null);

/// <summary>
/// Used to make a Post request to a specified url
/// </summary>
/// <param name="url">The target url</param>
/// <param name="method">The Http method</param>
/// <param name="data">The object to send to the api</param>
/// <returns>Returns a string</returns>
public async Task<string> MakeApiCall(string url, HttpMethod method, object data)

    // Create our local variables
    var client = new HttpClient();
    var user = Session["AccessToken"];
    var authenticating = user == null;

    // If we are not authenticating, set our auth token
    if (!authenticating)
        client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Session["AccessToken"].ToString());

    // Check to see what HTTP method is being used
    switch (method)
        case HttpMethod.POST:

            // If we are POSTing, then perform a post request
            return await PostRequest(client, url, data, authenticating);

            // If we are GETing, then perform a get request
            return await GetRequest(client, url);

#region Helper methods

/// <summary>
/// Posts data to a specifed url
/// </summary>
/// <param name="client">The HttpClient used to make the api call</param>
/// <param name="url">The target url</param>
/// <param name="data">The object to send to the api</param>
/// <param name="authenticating">Used to set the content type when authenticating</param>
/// <returns>Returns a string</returns>
private async Task<string> PostRequest(HttpClient client, string url, object data, bool authenticating)

    // If the data is a string, then do a normal post, otherwise post as json
    var response = (data is string) ? await client.PostAsync(this.apiUrl + url, new StringContent(data.ToString())) : await client.PostAsJsonAsync(this.apiUrl + url, data);

    // If we are authenticating, set the content type header
    if (authenticating == true)
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded");

    // Handle our response
    return await HandleResponse(response);

/// <summary>
/// Gets data from a specifed url
/// </summary>
/// <param name="client">The HttpClient used to make the api call</param>
/// <param name="url">The target url</param>
/// <returns>Returns a string</returns>
private async Task<string> GetRequest(HttpClient client, string url)

    // Perform the get request
    var response = await client.GetAsync(this.apiUrl + url);

    // Handle our response
    return await HandleResponse(response);

/// <summary>
/// Used to handle the api response
/// </summary>
/// <param name="response">The HttpResponseMessage</param>
/// <returns>Returns a string</returns>
private async Task<string> HandleResponse(HttpResponseMessage response)

    // Read our response content
    var result = await response.Content.ReadAsStringAsync();

    // If there was an error, throw an HttpException
    if (response.StatusCode != HttpStatusCode.OK)
        throw new HttpException((int)response.StatusCode, result);

    // Return our result if there are no errors
    return result;


The issue I have with this approach is the HandleResponse method. When an API call is made, if the call fails it lands on this line:

// If there was an error, throw an HttpException
if (response.StatusCode != HttpStatusCode.OK)
    throw new HttpException((int)response.StatusCode, result);

which in turn is captured by the Application_Error method inside Global.asax. The problem with this, is that because this is an API call the controller can't redirect to the ErrorController...

So my question is:

  1. Can I somehow ignore the Global.asax error handling and just return JSON so that my JavaScript can decide what to do with the error OR
  2. Is there a better way of doing this?

If you have any questions, please ask. I have tried to make sure the post is not just a wall of text.

How to Save Multiple Tags to Database [Asp Mvc]

I'm trying to save multiple tags to my database .

Here is my classes :

public partial class Book
    public int Book_id { get; set; }


    public virtual IList<Tag> Tags { get; set; }


and here is the tag class :

 public class Tag
    public virtual int Id
    { get; set; }

    public virtual string Name
    { get; set; }

    public virtual string UrlSlug
    { get; set; }

    public virtual string Description
    { get; set; }

    public virtual IList<Book> Books
    { get; set; }

My view (Create post View):

<div class="form-group">
                    @Html.LabelFor(model => model.Tags, htmlAttributes: new { @class = "control-label col-md-2 col-md-offet-3" })
                    <div id="tags">
                        @Html.TextBoxFor(model => model.Tags, new { htmlAttributes = new { @class = "form-control" } })

My controller :

    public async Task<ActionResult> Create(Book model)
        if (ModelState.IsValid)

            Collection<Tag> postTags = new Collection<Tag>();
            var s = model.Tags.ToString();
            string[] newTags = s.Split(',');

            foreach (var val in newTags)
                Tag iTag = new Tag
                    Name = val

            model.Tags = postTags;

            await db.SaveChangesAsync();
            return RedirectToAction("Index");

        return View(model);


When I added a new post , and checked the DB the BookTagMap table is working well , but the tags table save the tag name like this :



TagBooks Table

How can we perform CRUD operations for multiple roles in one controller in mvc3?

I have more than one roles of user.that is distributor, micro-distributors, dealers , users and so on.I need to create the CRUD operations for all these roles.They can add the subsequent level users and itself. that is if we are a dealer, then we can add our bottom party user and we can add ourself account. how can we perform these in mvc3 project?

How can we check the whole sql database for login username and password in mvc3 c#?

I have more than one table in my sql server database. Each table is for each users named developers, designers, users and so on. My home page contains a login screen. When a user tries to login with their username and password, then it automatically checks whether the username and password belongs to the database. If yes, it redirects to a page, else prompts an error.

I need whole database check instead of one table because there is only one login page for all users. Thanks!

Is it possible to get form iD in mvc

Is it possible to find the formID in jquery file if i ddnt explicitly specify and id in razor view

@using (Html.BeginForm()) Here i don't want to specify an id of th form and on click of a button i want to submit this form from my jquery file.

Here is my view and

 @using (Html.BeginForm())

This jquery doesnt work.

$(".TestCreateSubmit").click(function (e) {
    var form = this;//this doesnt work
    form.submit();  //this doesnt work

Is it possible to invoke the Submit() method of the form if id is not specified

binding http handler to non existing physical file

Is it possible to bind a httphandler like this

  <add verb="*" path="handler1.ashx" name="MvcApplication13.HelloWorldHandler" type="MvcApplication13.HelloWorldHandler, MvcApplication13"/>

Here handler1.ashx does not exist physically. If user request for that file,it should be handled by MvcApplication13.HelloWorldHandler


vendredi 5 février 2016

How to make a view count in ASP MVC

My Inquire about the unique view (watch) count for each post .

For example : for each post , i should have an attribute that tells me the view count 'till now ..

Here is my class :

public partial class Book
    public int Book_id { get; set; }

    [Display(Name ="User Name")]
    public string User_ID { get; set; }

    [Display(Name = "Title Name")]
    [StringLength(70,MinimumLength =3)]
    public string Book_name { get; set; }

    [Display(Name = "Edition")]
    [Range(1, 20)]
    public int Edition { get; set; }

    [Display(Name = "Category Name")]
    public int Category_id { get; set; }

    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]    
    [Display(Name = "Publish Date")]
    public DateTime Publish_date { get; set; }

    [Display(Name = "Author Name")]
    public string Author_name { get; set; }

    [Display(Name = "Cover Image")]
    public string Book_Image { get; set; }

    [StringLength(128,MinimumLength =8)]
    [Display(Name = "Download Link")]
    public string Download_Link { get; set; }

    [Display(Name = "Upload Pdf")]
    public string pdf_file { get; set; }

    [Column(TypeName = "text")]
    [Display(Name = "Description")]
    public string Book_Description { get; set; }

    public virtual Category Category { get; set; }

So please if anyone now a way or can help with that , it will be great , thanks

jeudi 4 février 2016

Autofac - InstancePerLifeTimeScope and the life time of the objects

I am very new to Autofac dependency injection and I got these questions related to my project. I have gone through many articles but I am not getting a clear picture on some of the questions I have. Mine is a service application on .Net REST API. I am doing instance registration in App_Start module as shown below.

private static IContainer RegisterServices(ContainerBuilder builder)
            Container = builder.Build();
            return Container;


My service layer is "MessageService" and there I am performing all the DB and other integration operations and getting the instances through constructor injection. These are the questions I have around this implementation.

  1. I am using InstancePerLifeTimeScope for all my registrations. Is this is the right approach? After the life cycle of each controller request (http request), will these instances will be automatically disposed?
  2. Do we need to manually implement any Dispose operation on any of these instances? ( I don’t have any unmanaged objects in my code)
  3. From the service method, I need to create a fire&forget thread as well using Task.Run(). What is the best approach to supply instances to this fire&forget thread? If I use InstancePerLifeTimeScope, I can see that new thread also getting the same instances that available through the service class so I am just confused when these instances will be disposed?

JSON object not correctly sent to my ASP.NET MVC controller, missing properties

I have an issue with passing a JSON objject to my ASP.NET MVC controller.

JSON is set in JS this way:

 jsonChildren = '{ "childImproItems" : [{ "Theme":"tralalali"  }, { "Theme":"tralalali"  }]}';
           url: url,  
            type: 'POST',
            data: JSON.parse(jsonChildren),
            success: function (result) {
            error: function (result) {

Inside my controller:

public int MyMethod(String typeName, SelectOptionsViewModel id) {
  return 0;

Concerned Model classes are as follows:

public class SelectOptionsViewModel {
  public List<ChildImproItemViewModel> childImproItems { get; set; }


public class ChildImproItemViewModel {
  public string Theme { get; set; }

The debugger correctly routes me to my controller and correctly interprets the JSON as a SelectOptionsViewModel instance. It correctly sets its childImproItems property with a list of 2 objects. But the Theme property of the 2 childImproItems objects is null although they are supposed to be set to a dummy value in my example. The same happens with the other properties.

Do you guys see where is my mistake?

thx in advance.

mercredi 3 février 2016

Could not load file or assembly - mvc app

trying to work on a mvc 3 app, using visual studio 2010. The app compiles fine. However, failing at runtime.

Could not load file or assembly 'InnVue.BOA.RoomControl' or one of its dependencies. An attempt was made to load a program with an incorrect format.

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.BadImageFormatException: Could not load file or assembly 'InnVue.BOA.RoomControl' or one of its dependencies. An attempt was made to load a program with an incorrect format.

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.

Assembly Load Trace: The following information can be helpful to determine why the assembly 'InnVue.BOA.RoomControl' could not be loaded.

=== Pre-bind state information ===
LOG: DisplayName = InnVue.BOA.RoomControl
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: InnVue.BOA.RoomControl | Domain ID: 10
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper for more information and common solutions to this issue.
LOG: Appbase = file:///C:/Users/KHAN/Documents/GitHub/innvue/InnVue.InnDesk/InnVue.InnDesk/InnVue.InnDesk/
LOG: Initial PrivatePath = C:\Users\KHAN\Documents\GitHub\innvue\InnVue.InnDesk\InnVue.InnDesk\InnVue.InnDesk\bin
Calling assembly : (Unknown).
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\KHAN\Documents\GitHub\innvue\InnVue.InnDesk\InnVue.InnDesk\InnVue.InnDesk\web.config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Users/KHAN/AppData/Local/Temp/Temporary ASP.NET Files/root/41f4bb6c/382c05ac/InnVue.BOA.RoomControl.DLL.
LOG: Attempting download of new URL file:///C:/Users/KHAN/AppData/Local/Temp/Temporary ASP.NET Files/root/41f4bb6c/382c05ac/InnVue.BOA.RoomControl/InnVue.BOA.RoomControl.DLL.
LOG: Attempting download of new URL file:///C:/Users/KHAN/Documents/GitHub/innvue/InnVue.InnDesk/InnVue.InnDesk/InnVue.InnDesk/bin/InnVue.BOA.RoomControl.DLL.
ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated.

And the stack trace is :

[BadImageFormatException: Could not load file or assembly 'InnVue.BOA.RoomControl' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   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.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +21
   System.Reflection.Assembly.Load(String assemblyString) +28
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38

[ConfigurationErrorsException: Could not load file or assembly 'InnVue.BOA.RoomControl' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +738
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +217
   System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +130
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170
   System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +92
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +290
   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): Could not load file or assembly 'InnVue.BOA.RoomControl' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9942412
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +90
   System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +456

I have confirmed :

InnVue.BOA.RoomControl.dll is indeed 64bit dll

Assemblies referenced by InnVue.BOA.RoomControl.dll are also referenced by the main project.

Is there any way to track down exactly where this is breaking ? the information provided in stack trace is not very obvious .

Modal Popup not loading with url.action

I want to show a modal popup, but it's not loading in this case:

@Html.ActionLink( "Delete", "ResumeSubjects", new { id = s.rsID }, new { data_modal = "" })

How do I pass the data_modal in Url.action?

mardi 2 février 2016

Set all day events programatically in ICalander

I am a newbie using ICalander. I have a web application with '.ics' file

generator. Now i try to create a event details with this Calender. The events

have a StartDate and EndDate and StartTime and EndTime (event data from DB).

If StartTime and EndTime is empty, i want to All day event option in


Please help.

reCAPTCHA - WebException: The operation has timed out

Attempting to use the new reCaptcha on my website but it's timing out during the validation. Here is the stack trace;

[WebException: The operation has timed out]
   System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) +283
   System.Net.WebClient.DownloadString(Uri address) +100
   System.Net.WebClient.DownloadString(String address) +29
   PROJECTNAME.Controllers.AboutController.validate(String name, String company, String phone, String email, String subject, String body, Nullable`1 remember) +106
   lambda_method(Closure , ControllerBase , Object[] ) +360
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +182
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +56
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +256
   System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +22
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +190
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +311
   System.Web.Mvc.Controller.ExecuteCore() +105
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +87
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
   System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +34
   System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +19
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +31
   System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +23
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +59
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9658396
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

This is the basic controller that i'm using to validate;

public ActionResult validate(string name, string company, string phone, string email, string subject, string body, bool? remember)

    var r = Request["g-recaptcha-response"];

    string reply;
    using (var wc = new System.Net.WebClient())
        reply = wc.DownloadString(string.Format(
        "}", SECRETKEYREMOVED, r));


    var captchaResponse = JsonConvert.DeserializeObject<CaptchaResponse>(reply);

    if (captchaResponse.Success == "true")
            Do stuff to send msg

            return RedirectToAction("ContactSent");
        catch (Exception ex)
            ViewData.ModelState.AddModelError("_FORM", ex.ToString());



        return RedirectToAction("ContactFailed");

    return View();

And the Model...

namespace TVCWeb.Models
    public class CaptchaResponse:viewModelBase
        public string Success { get; set; }

        public List<string> ErrorCodes { get; set; }

And also the View..

    @using (Html.BeginForm())


<div class="g-recaptcha" data-sitekey="datakeyremoved"></div>

        <div class="contactButtons">
            <input type="submit" value="Send" id="send" />

I am struggling to find where the server is hanging with the validation. The contact form works perfectly fine without the Captcha but when added it just hangs. I've tried out a few different ways to do this but none of them seem to be working. Is it possible it's an issue with the Web Hosts?

Any help out there? Thanks

MVC How to pass a model beetwen two different applications

Here is the thing! At the company where I work there are two applications builted in MVC, one of these is used for loguin and some special funtionalities and the other one is used for global user's (I don't realy know why there are two applications. I think it most be just one).

Well, that is the context, now what I need to do is to pass a model from one application to the other, the problem is that I need to do it in the Action method to another Action method. The only method I found to do it is Redirect() but it only receive an url string and I can't pass query string's.

Is there a way to pass an encrypted model(I'm not sure if encrypted is the right word, but I think you know what I mean)?

MVC manipulate URL (routing), is it possible?

I have a website that use this pattern.

My question is now, i need to create a subsite that going to be with this URL pattern, i have tried to change the routing without success.

How can i inject the companyname in the URL without breaking my current routing?

Thanks Niden

Using viewbag in view

In my Controller I've created a viewbag attribute named OptionList in which I created one string with some options for a selectpicker I'd like to use in my view.

foreach(Uren_IssueType type in IssueType_List)
    optionList = optionList + "<option>" + type.TypeNaam + "</option>";
ViewBag.OptionList = optionList;

Because it's a dynamically created selectpicker (It's part of every row in a grid in which the rows can be added and removed dymanically) I want to add this optionlist to a string in which the selectpicker is created.

<td width=\"125\">
    <select class=\"form-control\" id=\"selectpicker\" name='selectpicker'>

But this code does work only the option are not displayed. It shows a empty dropdownlist. Can someone help me with how to create this selectpicker list from the viewbag string?

some one can please tell me what error i"m doing, below is my code

Models.student stu = dc.GetTable<Models.student>().Single(x => == Convert.ToInt32(id));
return View("index", "home");

call method from other controller that uses Request["name"] variable

I am using MVC. My HTML code is:

<form action="/MobilesController/SaveMobilesAd">
      <input type="text" name="brand" />
      <input type="text" name="color" />
      <!-- other stuff -->
      <input type="submit" />

There are more than 10 attributes like brand,color and I have to input data on 15 different pages. To avoid code redundancy I made a function MyAd() implemented all my logic in this function and I just call this function wherever I needed.

public class AdController: Controller
         public void MyAd()
              string brand = Request["brand"];
              string color = Request["color"];
              //other stuff. take data from Request variables and save in database.

Now to use MyAd() in another contoller:

public class MobilesController:Controller
     AdController ad = new AdContoller();
     public ActionResult SaveMobilesAd()
           //some stuff.

Now the problem is when i call MyAd() in another controller it gives exception

Object reference not set to an instance of an object

on Request["brand"] . How can i avoid this exception or this there any other way to achieve this?

lundi 1 février 2016

How to submit form when datepicker value is older than today in mvc?

I am using partial view to add a group of controls dynamically into my form.
Code for adding controls in javascript:

$doc.on('click', '#btnAddReceipt', function (e) {
function AddReceipt(stepName) {
        type: "GET",
        async: false,
        url: '/claims/new-receipt/' + stepName,
        success: function (data, textStatus, jqXHR) {
            var element = $(data);
            $("#" + stepName + "ReceiptsContainer table tbody").append(element);
//please note here I am attaching datepicker class to my date textbox
            $("#" + stepName + "ReceiptsContainer .datepick").datepicker({
                dateFormat: "dd/mm/yy",
                autoclose: true

            $("#" + stepName + "ReceiptsContainer .receiptCountry").on('blur', function(){

            setTimeout(function () {
            }, 100);

Partial View:

    @using (Html.BeginCollectionItem(sectionName, @Model.Guid.ToString()))
        <td>@Html.EditorFor(t => t.ReceiptDescription, new { htmlAttributes = new { @class = "form-control" }})</td>
        <td>@Html.TextBoxFor(t => t.CountryOnReceipt, new { @class="form-control receiptCountry" })</td>
        <td>@Html.TextBoxFor(t => t.DateOnReceipt, new { @class = "datepick form-control" } )</td>
        <td>@Html.TextBoxFor(t => t.CurrencyOfAmount, new { @class = "form-control amountCurrency", @readonly = "readonly" })</td>
        <td>@Html.EditorFor(t => t.AmountClaimed, new { htmlAttributes = new { @class = "form-control numericOnly" } })</td>
        <td><button type="button" class="clsDeleteClaimReceipt btn btn-danger" id=@String.Format("btnDeleteClaimReceipt{0}", Model.Guid) data-id="@Model.Guid" onclick="DeleteClaimReceipt($(this))">Remove</button></td>

So far this working as expected. But the problem is, whenever I try to submit my form (inside which this partial view is being rendered) with an Old Date (older date than today), it does not submitting the form. But If I provide a date like today or future date, it works fine.
My model:

    public class ClaimReceipt
        public Guid Guid { get; set; }

        [PlaceHolder("Enter Receipt Description")]
        public string ReceiptDescription { get; set; }

        [PlaceHolder("Enter Country On Receipt")]
        public string CountryOnReceipt { get; set; }

//I tried applying/removing below, but no luck in either case
        //[PlaceHolder("Enter Date Of Receipt")]
        //[Display(Name = "Date Of Receipt")]
        //[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
        public DateTime? DateOnReceipt { get; set; }

        public string CurrencyOfAmount { get; set; }

        [PlaceHolder("Enter Amount Claimed")]
        [Range(0, double.MaxValue, ErrorMessage="Please enter valid amount")]
        public decimal AmountClaimed { get; set; }

        public string SectionName { set; get; }

        public ClaimReceipt()
            this.Guid = this.Guid == Guid.Empty ? Guid.NewGuid() : this.Guid;

I am using VS2013, Asp.Net MVC, Razor view.

MVC3 Unobtrusive Validation not rendering appropriate attributes

I am currently using the following code for my validation

// Model
public class NominationsViewModel{

    public string Award {get; set;}

// View
    @Html.LabelFor(model => model.Award)
    @Html.RadioButtonFor(model => model.Award, "Award-1")

with expectations that it will output something like the following

<input data-val="true" data-val-required="The Award Field Is Required." id="Award" name="Award" value="award-1" type="radio">

But Instead it outputs this,

<input id="Award" name="Award" value="award-1" type="radio">

which does not include the data-val* attributes that I need in order to perform my validation.

My Web.config does happen to have the ClientValidation and UnobtrusiveJavaScript tags set to true. So I don't happen to see what gives.

Any help??

How to make one word bold in a label in ActiveReport?

How to make one word bold in a label in GrapeCityActiveReport 7?

For Example

Jackson John.

My version ActiveReports 7 File Version 7.1.7470.0 Assembly Version 7.1.7470.0