samedi 31 octobre 2015

Is JQuery clear?

I learn JQuery and made a simple app to show, add, delete, update product. If someone can review my code.

 function getAll() {
$.getJSON("../api/products")
    .done(function (data) {
        // On success, 'data' contains a list of products.
        $.each(data, function (key, item) {
            // Add a list item for the product.
            $('<li>', { text: formatItem(item) }).appendTo($('#products'));
        });
    });
function find() {
var id = $('#productID').val();
$.getJSON("../api/products" + '/' + id)
    .done(function (data) {
        $('#product').text(formatItem(data))
    })
    .fail(function (jqXHR, textStatus, err) {
        $('#product').text('Error: ' + err);
    });

}

function findByCategory() {
var id = $('#categoryID').val();
$.getJSON("../api/products" + '?category=' + id)
.done(function (data) {
    // On success, 'data' contains a list of products.
    $.each(data, function (key, item) {
        // Add a list item for the product.
        $('<li>', { text: formatItem(item) }).appendTo($('#productByCategory'));
    });
});

}

function add() {
var id = parseInt($('#newProdId').val());
var name = $('#newProdName').val();
var category = $('#newProdCategory').val();
var price = parseFloat($('#newProdPrice').val());
var description = $('#newProdDescription').val();
var product = { id: id, Name: name, Category: category, Price: price, Description: description };
$.ajax({
    type: "POST",
    data: JSON.stringify(product),
    url: "../api/products/",
    contentType: "application/json",
    dataType: 'json',
    //success: this.document.location.reload()
}).done(function (data) {
    $('#addProduct').text("Product added - " + formatItem(data));
}).fail(function (jqXHR, textStatus, err) {
    $('#addProduct').text('Error: ' + err);
});

}

function update() {
var id = parseInt($('#prodId').val());
var name = $('#prodName').val();
var category = $('#prodCategory').val();
var price = parseFloat($('#prodPrice').val());
var description = $('#prodDescription').val();
var product = { id: id, Name: name, Category: category, Price: price, Description: description };
$.ajax({
    type: "PUT",
    data: JSON.stringify(product),
    url: "/api/products/" + id,
    contentType: "application/json",
    dataType: 'json',

}).done(function (data) {
    $('#editProduct').text("Product edited - " + formatItem(data));
}).fail(function (jqXHR, textStatus, err) {
    $('#editProduct').text('Error: ' + err);
});

}

function del() {
var id = $('#delBookId').val();
$.ajax({
    type: "DELETE",
    url: "../api/products" + '/' + id,
    contentType: "application/json;charset=utf-8",
}).done(function (data) {
    $('#delBook').text("DELETED - " + formatItem(data));
}).fail(function (jqXHR, textStatus, err) {
    $('#delBook').text('Error: ' + err);
});

}

function formatItem(item) {
return item.id + '- ' + item.Name + '- ' + item.Category + '- ' + item.Price + '- ' + item.Description;

}

 public class Product
{
    [Required]
    public int id { get; set; }
    [Required]
    [MinLength(3), MaxLength(30)]
    public string Name { get; set; }
     [Required]
    [MinLength(3)]
    public string Category { get; set; }
     [Required]
     [Range(0.01, 1000)]
    public double Price { get; set; }
     [Required]
     [MinLength(10)]
    public string Description { get; set; }
}

  public class ValidationFilterAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
        {
            if (actionContext.ModelState.IsValid)
            {
                base.OnActionExecuting(actionContext);
            }
            else
            {
                // Either throw an exception or return a response, without calling the base
                actionContext.Response = actionContext.Request.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest,
                    actionContext.ModelState);
                //throw new HttpResponseException(
                //    actionContext.Request.CreateErrorResponse(System.Net.HttpStatusCode.BadRequest,
                //    actionContext.ModelState)
                //    );
            }
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            base.OnActionExecuted(actionExecutedContext);
        }
    }

   public class ProductsController : ApiController
{
     public static List<Product> products = new List<Product>
    {
        new Product
        {
            id=1,
            Name="BMW",
           Category="Cars",
           Description="A brand new car",
           Price=500.00

        },
        new Product
        {
           id=2,
            Name="Subaru",
           Category="Cars",
           Description="A car year 2009, 4000 km",
           Price=200.00
        },
         new Product
        {
           id=3,
            Name="Porshe",
           Category="Cars",
           Description="A car year 2011, 2000 km",
           Price=800.00
        },
         new Product
        {
           id=4,
            Name="BMX",
           Category="Bicycles",
           Description="A brand new bycicle",
           Price=100.00
        },
         new Product
        {
           id=5,
            Name="Equalizer",
           Category="Bicycles",
           Description="A brand new bycicle",
           Price=200.00
        },
        new Product
        {
           id=6,
            Name="Cosm",
           Category="Books",
           Description="A detective",
           Price=50.00
        },

    };


    //get all products
    //[Route("api/products/{id}")]
     public HttpResponseMessage Get()
     {
         if (products==null)
         {
                return Request.CreateResponse(HttpStatusCode.NotFound);
         }
         else
         {
             return Request.CreateResponse(HttpStatusCode.OK, products);
         }

    }

    // search one product
    //[Route("api/products/{id}")]
    public HttpResponseMessage Get(int id)
    {
        var searchProduct = products.Where(x => x.id == id).FirstOrDefault();

        if (searchProduct == null)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.OK, searchProduct);
        }
    }

    //get a list of products in category

    public HttpResponseMessage Get(string category)
    {
        var searchProdInCategory = products.Where(x => x.Category == category);
        if (searchProdInCategory == null)
        {
            return Request.CreateResponse(HttpStatusCode.NotFound);
        }
        else
        {
            return Request.CreateResponse(HttpStatusCode.OK, searchProdInCategory);
        }

    }

    // add new product
   [ValidationFilterAttribute]
    public System.Web.Http.IHttpActionResult Post([FromBody]Product newProduct)
    {  


            products.Add(newProduct);
        IHttpActionResult response;

        try
        {


            response = CreatedAtRoute("DefaultApi", new { id = newProduct.id }, newProduct);

        }
        catch (Exception ex)
        {
            return InternalServerError(ex);
        }

        return response;
    }

    // update a product

    [ValidationFilterAttribute]
    public HttpResponseMessage Put(int id,[FromBody]Product updatedProduct)
    {
        HttpResponseMessage response;
        var product = products.Where(x => x.id == id).FirstOrDefault();
        if (product == null) // product not found
        {
            products.Add(updatedProduct);
            response = Request.CreateResponse(HttpStatusCode.OK);

        }
        else
        {

                //product.Category = updatedProduct.Category;
                //product.Description = updatedProduct.Description;
                //product.Name = updatedProduct.Name;
                //product.Price = updatedProduct.Price;

               products.Remove(product);
               products.Add(updatedProduct);

                response = Request.CreateResponse(HttpStatusCode.OK);


        }

        return response;
    }

    // delete a product
    //[Route("api/products/{id}")]
    public HttpResponseMessage Delete(int id)
    {
        HttpResponseMessage response;
        var product = products.Where(x => x.id == id).FirstOrDefault();
        if (product == null) // product not found
        {
            response = Request.CreateResponse(HttpStatusCode.NotFound);
        }
        else
        {
            try
            {
                products.Remove(product);
                response = Request.CreateResponse(HttpStatusCode.OK);
            }
            catch (Exception)
            {
                response = Request.CreateResponse(HttpStatusCode.InternalServerError);
            }
        }

        return response;
    }
}

public class IndexController : Controller { // GET: Index public ActionResult Index() { return View(); } }

 public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();
        config.Filters.Add(new ValidationFilterAttribute());
        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

 public class WebApiApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);
        AreaRegistration.RegisterAllAreas();
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

How to pass a simple List

I have some thing like that:

@model List<string>@{
ViewBag.Title = "Details";}<h2>Details</h2><div>
<hr />
<dl class="dl-horizontal">

    <dt>
        @Html.DisplayName("Name")
    </dt>

    <dd>
        @Html.DisplayFor(model => model.ElementAt(0))
    </dd>

    <dt>
        @Html.DisplayName("Document")
    </dt>

    <dd>
        @Html.DisplayFor(model => model.ElementAt(1))
    </dd>
</dl></div><p>
@Html.ActionLink("Edit", "Edit", new { /* id = Model.PrimaryKey */ }) |
@Html.ActionLink("Back to List", "Index")

I know that it is wrong but how i can take 2 elements from LIST?

vendredi 30 octobre 2015

return file result to ajax c#

I want to generate pdf using rdlc. It works fine when function for generating pdf is called on submit button of form. but when I call it using ajax, it returns correct data but I dont know how to show it in browser.

//This works fine
    [HttpPost]
    public ActionResult Create(CustomerInputModel UpdatedInputModel,FormCollection fc)
    {
           PrintPOFILE(UpdatedInputModel);
            return View(UpdatedInputModel); 
    }  

 //Render the report
 public FileResult PrintPOFILE(CustomerInputModel model)
    {
        renderedBytes = localReport.Render(
            reportType,
            deviceInfo,
            out mimeType,
            out encoding,
            out fileNameExtension,
            out streams,
            out warnings);

        //FileStream fs = new FileStream(filePath, FileMode.Create);
        using (FileStream fs = new FileStream(Server.MapPath("~/download/") + FileName + ".pdf", FileMode.Create))
        {
            fs.Write(renderedBytes, 0, renderedBytes.Length);
        }

        Response.ClearHeaders();
        Response.ClearContent();
        Response.Buffer = true;
        Response.Clear();
        Response.ContentType = "application/pdf";
        Response.AddHeader("Content-Disposition", "inline; filename=" + FileName + ".pdf;");

        Response.WriteFile(Server.MapPath("~/download/" + FileName + ".pdf"));
        Response.Flush();
        Response.Close();
        Response.End();

        string PdfUrl = Server.MapPath("~/download/" + FileName + ".pdf");
  return File(PdfUrl, "application/pdf");
    }

but when I call this function from ajax,

 $("#PrintBtn").click(function (){
 var id = $("#Id").val();
     $.ajax({
            url: "/Customer/PrintFile",
            type: "POST",
            data: {Id : id},
            success: function (data) 
            {
                alert(data);                        

                window.open("http://localhost:51035/download/"+data,"_blank");


            }
        });
      //  alert("Print");
    });
</script>

 //Controller action
 [HttpPost]
    public ActionResult PrintFile(string Id)
    {
        int id = Convert.ToInt32(Id);           
        PrintPOFILE(PrintModelObj );
        return View(PrintModelObj );
    }

alert(data); shows unicode characters but I want pdf file to open in new tab of browser.

Date & time is not inserted proper for special price while add product in nopcommerc

I am using nopcommerce version 3.60 & my database is on sql server 2012.my store date time is UTC+5.30 that i have set after refer this post http://ift.tt/1GD11qr

i have try to enter special price start date is 1-jan-2015 and special price end date is 31-jan-2016 and try to save this but i got error of "The value '1/31/2016 12:00 AM' is not valid for Special price end date." that i didn't get it why this comes i have enter proper and in text box it shows 1/31/2016 12:00 AM and if i change it with 31/1/2015 12:)) AM it will be saved and show in special price end date textbox is 31-Jan-16 12:00:00 AM. so i am facing this issue. please provide me some setting for this bug.

So it is Nopcommerce bug. is any one have face this issue tell me that. and also checked in database of product table it has datatype is datetime.

FileExtension Validation using custom validation creates duplicate and invalid data-* attributes

This question raises after what I've tried from the answer mentioned in my previous question. I followed this article exactly the same way but validations for image files instead of doc files mentioned in the article.

Description: I have a input control of type=file which is to upload image files and this exists in one of the partialview. The partialview gets loaded on click of a button. And to apply validations mentioned in model, explicitly add unobtrusive to the form. But after following all the set-ups mentioned in the above-said article, I am not able to validate the file on submit also the the data-* created by unobtrusive validation is quite fishy or better say invalid. Below is the code to show how my setup looks like and here is the html which gets created by unobtrusive validation with invalid data-* attribute, may be because of which the validation fails to happen.

<input data-charset="file" data-val="true" data-val-fileextensions="" data-val-fileextensions-fileextensions="png,jpg,jpeg" id="File" multiple="multiple" name="File" type="file" value="">

Load Partial View Js

$('.getpartial').on('click', function () {
    $('.loadPartial').empty().load('/Home/GetView',function () {
        var form = $('form#frmUploadImages');
        form.data('validator', null);
        $.validator.unobtrusive.parse(form);
        $(function () {
            jQuery.validator.unobtrusive.adapters.add('fileextensions', ['fileextensions'], function (options) {
                var params = {
                    fileextensions: options.params.fileextensions.split(',')
                };
                options.rules['fileextensions'] = params;
                if (options.message) {
                    options.messages['fileextensions'] = options.message;
                }
            });

            jQuery.validator.addMethod("fileextensions", function (value, element, param) {
                var extension = getFileExtension(value);
                var validExtension = $.inArray(extension, param.fileextensions) !== -1;
                return validExtension;
            });

            function getFileExtension(fileName) {
                var extension = (/[.]/.exec(fileName)) ? /[^.]+$/.exec(fileName) : undefined;
                if (extension != undefined) {
                    return extension[0];
                }
                return extension;
            };
        }(jQuery));
    })
})

ModelClass

public class ImageUploadModel
{
    [FileValidation("png|jpg|jpeg")]
    public HttpPostedFileBase File { get; set; }
}

View

@model ProjectName.Models.ImageUploadModel

@using (Html.BeginForm("UploadImages", "Admin", FormMethod.Post, htmlAttributes: new { id = "frmUploadImages", novalidate = "novalidate", autocomplete = "off", enctype = "multipart/form-data" }))
{
    <div class="form-group">
        <span class="btn btn-default btn-file">
            Browse @Html.TextBoxFor(m => m.File, new { type = "file", multiple = "multiple", data_charset = "file" })
        </span>&nbsp;
        <span class="text-muted" id="filePlaceHolder">No files selected</span>
        @Html.ValidationMessageFor(m => m.File, null, htmlAttributes: new { @class = "invalid" })
    </div>
    <div class="form-group">
        <button class="btn btn-primary addImage pull-right">
            <i class="fa fa-upload"></i> Upload
        </button>
    </div>
}

and finally my CustomFileValidation class

[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class FileValidationAttribute : ValidationAttribute, IClientValidatable
{
    private List<string> ValidExtensions { get; set; }

    public FileValidationAttribute(string fileExtensions)
    {
        ValidExtensions = fileExtensions.Split('|').ToList();
    }

    public override bool IsValid(object value)
    {
        HttpPostedFileBase file = value as HttpPostedFileBase;
        if (file != null)
        {
            var fileName = file.FileName;
            var isValidExtension = ValidExtensions.Any(y => fileName.EndsWith(y));
            return isValidExtension;
        }
        return true;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientFileExtensionValidationRule(ErrorMessage, ValidExtensions);
        yield return rule;
    }
}
public class ModelClientFileExtensionValidationRule : ModelClientValidationRule
{
    public ModelClientFileExtensionValidationRule(string errorMessage, List<string> fileExtensions)
    {
        ErrorMessage = errorMessage;
        ValidationType = "fileextensions";
        ValidationParameters.Add("fileextensions", string.Join(",", fileExtensions));
    }
}

Passing Guid In Edit Method

[HttpGet]
public ActionResult Edit(Guid UserId)
{
    ViewBag.UserName = new SelectList(db.Users.ToList(), "UserId", "UserName");
    ViewBag.Role = new SelectList(db.Roles.ToList(), "RoleId", "RoleName");
    UsersRoles usersRoles = db.UsersRoles.Find(UserId);
    return View(usersRoles);
}

[HttpPost]
public ActionResult Edit(UsersRoles usersRoles)
{
    if (ModelState.IsValid)
    {
        db.Entry(UsersRoles).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(usersRoles);
}

I Have created Edit method as Above and UserId Is not passing in above method . Following Error Is Generated How can i Fix It?

The parameters dictionary contains a null entry for parameter 'UserId' of non-nullable type 'System.Guid' for method

jeudi 29 octobre 2015

Override default model validation message without inheriting

There are multiple data annotation attributes in C#, such as [Required], [MaxLength] etc, each of which has it own default validation message.

What I trying to achieve here is to override the default validation message without inheriting the attribute in following way. I need a base for this, and not simply put [MaxLength(5, Error Message = "Custom Error Message")]. Put in in simple term, when i decorate with [MaxLength(5)], the output of model validation error should be "Custom Error Message" instead of default error message. What I have achieve now is need to use [MyMaxLength(5)] instead.

public class MyMaxLengthAttribute : MaxLengthAttribute
{
    public MyMaxLengthAttribute(int length) : base(length)
    {
        ErrorMessage = "Custom Error Message"
    }
}

How to count number of times website visited and online users in MVC

I need to find count number of times website visited and online users.

My code:

Global.asax

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


        // Code that runs on application startup
        Application["SiteVisitedCounter"] = 0;
        //to check how many users have currently opened our site write the following line
        Application["OnlineUserCounter"] = 0;
    }

    void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started
        Application.Lock();
        Application["SiteVisitedCounter"] = Convert.ToInt32(Application["SiteVisitedCounter"]) + 1;
        //to check how many users have currently opened our site write the following line
        Application["OnlineUserCounter"] = Convert.ToInt32(Application["OnlineUserCounter"]) + 1;
        Application.UnLock();
    }

    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends.
        // Note: The Session_End event is raised only when the sessionstate mode
        // is set to InProc in the Web.config file. If session mode is set to StateServer
        // or SQLServer, the event is not raised.
        Application.Lock();
        Application["OnlineUserCounter"] = Convert.ToInt32(Application["OnlineUserCounter"]) - 1;
        Application.UnLock();
    }

Home Controller contains the following code.I got an error on System.Net.Mime.MediaTypeNames.Application.

   [HttpGet]
   public ActionResult Index()
    {
        ViewBag.noofsitesvisited = "No of times site visited=" + System.Net.Mime.MediaTypeNames.Application["SiteVisitedCounter"].ToString();
        ViewBag.onlineusers = "No of users online on the site=" + System.Net.Mime.MediaTypeNames.Application["OnlineUserCounter"].ToString();
    }

it did not work

mercredi 28 octobre 2015

Asp.net MVC 3 Ienumerable and datatable

I am implementing asp.net mvc 3 for my terrorist detection application. i have certain queries as follows
1. I am using ODP.NET, so the dataset which i get from procedure should be passed as Ienumerable, list or datatable from model to controller

Override max length error message in MVC

I am trying to override the max length error message in ASP.net MVC. Basically, I would like to make the error message string as follow:

[DisplayName] length should not be more than [x]. However, I do not know how to include the displayname attribute value inside.

public class MyMaxLengthAttribute : MaxLengthAttribute
{
    public MyMaxLengthAttribute(int length) : base(length)
    {
        ErrorMessage = "What should I input here"
    }
}

mardi 27 octobre 2015

Azure Web API Apps and Error Responses

I've got a simple REST Service deploy as an Azure API App. When my REST service returns a 200 response is ok. But if my app returns a non 200 response I get different results between running in IIS Express and Azure. In IIS Express it will return:

Http Response Code: 412 {"formattedAmount":"$60.00","amount":60.0,"message":"Sorry you cannot place bookings for more than 20 days in advance"}

Which is what I've coded it to do. When deployed to Azure it returns this document instead

{ "status": 412, "source": "http://ift.tt/1KEqj29 12:45:00&exitDate=2015-11-30 12:15:00&promoCode=", "message": "Sorry you cannot place bookings for more than 20 days in advance" }

What's doing this? IS there some kind of proxy in Azure that's changing the response to this?

Interesting it seems to only have the issue when the "Accept" request header is "application/json". If I change it to "text/xml" I get this which is what I would expect:

-3420.208333333333($3,420.21)Sorry you cannot place bookings for more than 20 days in advance

Am I doing something silly in my MVC Web API config or does Azure have some kind of proxy server and if so how do I stop it doing this?

Trying to display PDF stream to web page for printing

I am trying to take a memory stream that contains either HTML or PDF (my choice).

The issue that I am running into is that I cannot render this content to my page. The content will show on the page, but it all garbled on the screen. If I take that same stream and save it to a file and open it up it displays correctly.

Am I incorrectly setting something wrong when it returns from the server?

On my web page I have:

function getData()
{
        $.ajax({
            type: 'GET',
            url: '/Main/MyController/GetPrintData',
            data: {
                reportID: 1,
                format: 'pct',
                cumeReach: 'abc',
                showAddl: 'true',
                precision: 'false'
            },
            contentType: 'application/pdf' //'text/html'
        }).success(function (result) {
            $('#reportData').append(result);
        }).error(function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
        });
};

The HTML looks like this:

<html>
  <head>
     <title>Print3</title>
  </head>
  <body onload="getData();">
    <div id="reportData">

    </div>
  </body>
</html>

Html.Action InsufficientExecutionStackException

Can not figure out what is wrong with it. There are two views. TabOne that render another view TabTwo with help of @Html.Action("Index", new { some params }) and TabTwo that render itself with different model with help of same @Html.Action("IndexPortlet", new { some params })

It started fail due migration from MVC3 to MVC4 with exception:

   at System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()
   at System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
   at System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
   at System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
   at System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout)
   at System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag)
   at System.Web.Mvc.Controller.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
   at System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout)
   at System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
   at System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout)
   at System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag)
   at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
   at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BegavinProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
   at System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout)
   at System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag)
   at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
   at System.Web.Mvc.HttpHandlerUtil.ServerExecuteHttpHandlerWrapper.Wrap[TResult](Func`1 func)
   at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride)
   at System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage)
   at System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm)
   at System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter)
   at System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues)
   at SandBox.CorePolicy.V1_5.Views.Bootstrap.Edit.Views_Quotation_Products_CorePolicy_1_5_Edit_Bootstrap_TabDetails_cshtml.Execute() in c:\longpathtoview\TabTwo.cshtml:line 123
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
   at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
   at RazorGenerator.Mvc.PrecompiledMvcView.Render(ViewContext viewContext, TextWriter writer)
   at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
   at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)

While debugging TabTwo does not call Html.Action more that one time (whatever it does not hit breakpoint more than once). I've already google for this as well as checked Stackoverflow but everything 've found is that MVC4 Async controller do sync child method execution for Html.Action that can be issue in some cases. Still it doesn't help

Please, could you advise with any help?

IEnumerable

I'm having following controller

        [HttpGet]
        [ValidateInput(false)]     
        public ActionResult Create_Template(IEnumerable<ProductsPropertiesVM> model)
        {
            // new you have access to all the ID's of the selected items, for example
            IEnumerable<int> selectedIDs = model.Where(x => x.IsChecked).Select(x => x.Property_ID);

            return View(selectedIDs);
        }

I want bind that IEnumerable<int> selectedIDs data values to view

Once I run this on debug mode normally those selectedIDs appear like this

enter image description here

So I want to pass those IEnumerable data set to view first and then show or hide div sections according to that values on viewpage

if I able to to bind data to view, I have palnned to show or hide div sections like below (appreciate your suggestions)

 @{
        ViewBag.Title = "Create Templat";
    }
    <!DOCTYPE html>
    <html>
    <head>
        <title>Create a Templat</title>
    </head>
    <body>

        <div id="header"> .... </div>

        <div id="nav"> .... </div>

        <div id="section"> .... </div>

        <div id="footer"> .... </div>


    </body>
    </html>

    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
        @Scripts.Render("~/bundles/jqueryui")

    <script type="text/javascript">


            $(document).ready(function () {

                //using for loop read the array values index 0  to end:

                for(i=0;i<array.length();i++){

                if(array has value 1) $("#header").show()
                else $(#header").hide();

                if(array has value 2) $("#nav").show()
                else $("#nav").hide();

                if(array has value 3) $("#section").show()
                else $("#section").hide();

                .........

                }
});   

    </script> 
    }

So I'm looking for good way to do this

lundi 26 octobre 2015

Execution time of same code in onactionexecuting vs onactionexecuted

I have a base controller with onactionexecuted which has some code. I want to move that filter checking on onactionexecuting. can any performance issue be possible in that case?

dimanche 25 octobre 2015

AuthenticationManager.SignIn() is not signing in

I can get the valid user from the database, create the ClaimsIdentity and the SignIn method is called without error.

public ActionResult SignInConformation(SignInModel model)
{
    if (ModelState.IsValid)
    {
        var user = _userManager.Find(model.Username, model.Password);

        if (user == null)
        {
            ModelState.AddModelError("", "Invalid username and\\or password");
        }
        else
        {
            _authenticationManager.SignOut();
            var claimsIdentity = _userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
            _authenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, claimsIdentity);
            return RedirectToAction("Index", "Home");
        }
    }

    return View();
}

However, when I check if the user is signed in on the view like this:

<p>
    Current User: @if (User.Identity.IsAuthenticated)
                  {
                      @User.Identity.Name
                  }
                  else
                  {
                      @:Unknown
                  }
</p>

IsAuthenticated returns false.

samedi 24 octobre 2015

converting MVC EF to 3-Tiers Architecture model

I was working on my project using MVC3 & Entity framework and the model of my project was about my entity.emdx only. now i want to convert this project to 3-tiers architecture that will be about: (presentation layer :my old MVC project's views and controllers), (business layer:all operations related to data base), (data access layer: my entity framework(.emdx)), This is what i concluded,, and if i am correct then the model in the MVC project (presentation layer) will be empty ,,,is it possible in MVC that doesn't contain Models?, if i my thinking is wrong so, what is the correct thing to do?

vendredi 23 octobre 2015

Syntax for multiline variables

I am new to the Razor engine. What I am trying to accomplish is to set a local variable containing css classes. I would prefer to have this in a more readable format should anyone need to modify this later on.

What is the correct syntax to accomplish this? (I first tried myCSS = "...", then I attempted to use @Html.Raw method)

The only way I can get it to work is to keep everything on one line.

Currently I have:

@{ var myCSS = @Html.Raw("<style>table {border-collapse: collapse; } ...etc</style>"); }

I would like something more readable. Such as:

@{ var myCss = @Html.Raw("
<style>
   table {border-collapse: collapse; } 
   etc....
</style>
"); }

0x800a138f - Microsoft JScript runtime error: Object expected

iam working using MVC and Entity framework , I have a view that displsy data of "BloodDonors" table from database and i can filter them by their blood group value that selected by dropdownlist ,so i want after choosing specific blood group i call the controller function that filters and pass them to the view for displaying.But after runing i get that exception:[0x800a138f - Microsoft JScript runtime error: Object expected] beacause of JS code that i used in the view . Any help to handle that exception? this is the JS code that i use to call controller function in the view :

<script src="~/Scripts/jquery-1.8.16.min.js" type="text/javascript"></script>
<script src="~/Scripts/jquery-1.8.16.js" type="text/javascript"></script>
<script>
    debugger;
    $(document).ready(function () {
        $("#DONOR_BLOOD_GROUPE_ID").change(function () {
            $.ajax({
                type: 'POST',
                url: '@Url.Action("FilterdIndex", "DONOR")',
                dataType: 'html',
                data: { id: $("#DONOR_BLOOD_GROUPE_ID").val() },
                success: function (data) {            
                },
                error: function (ex) {
                    alert('Failed to retrieve' + ex);
                    }
            });
           return false;
       })
   });
    </script>

the dropdownllist that call onchange func:

@Html.DropDownList("DONOR_BLOOD_GROUPE_ID", null, "--Select--", new { onchange="FilterdIndex(this.value)" , AutoPostBack="True"})

and this is the controller function that i call using JS code:

public ViewResult FilterdIndex(int id)
        {
          ViewBag.DONOR_BLOOD_GROUPE_ID = new SelectList(db.BLOOD_GROUP, "GROUP_ID", "GROUP_NAME");

            return View(db.DONOR.Where(u => u.DONOR_ID == id));
        }

And this is the line where the debugger stopped

<select AutoPostBack="True" id="DONOR_BLOOD_GROUPE_ID" name="DONOR_BLOOD_GROUPE_ID" onchange="FilterdIndex(this.value)"><option value="">--Select--</option>

jeudi 22 octobre 2015

Convert this row_number query to Entity Frame Work Linq to Object query

Original query:

select min(id) as startid, max(id) as endid
from (select t.*, floor((row_number() over (order by id) - 1) / 200) as grp
      from t
      where t.x = y
      ) t
group by grp;

This is a follow up question of: Sql Range Groups Start and End Id

I'm wondering if it is possible to convert this to a Linq to Object query? I've tried looking around for ideas and played with .Skip() .Take() but was unable to get anything close to what I need. Thanks.

Edit: I would like the entire transaction to happen in the database. This will be a fairly large set of data and it would be best if I don't have to process it further in my application.

Error HRESULT E_FAIL has been returned from a call to a COM component on a MySQL Mvc3 project

I need to develop a MySQL MVC 3 project in Visual Studio 2013 Premium. I installed all the needed components off MySQL/Oracle. But when I try to create one, I get the next error.

"Error HRESULT E_FAIL has been returned from a call to a COM component".

Now I don't know which COM component. As far as I know, the only COM components it uses is Entity Framework and MVC. I suspect it is Entity Framework that is bitching. MySQL project only supports EF 5.0 of 6.0 but the most recent version of EF is 6.1.3, so I don't know if this could be the problem but I'm trying to be as open as possible.

The project doesn't create a model to interact with the database either (a child class of DbContext) either.

Does somebody have the solution to this? I have this problem on 2 different PC's already, both running on VS2013 Premium.

SelectList throwing "Object reference not set" error even after initializing in Constructor

I have below Model

public class UploadImageAlbum
{
    public UploadImageAlbum()
    {
       Albums = new SelectList(Enumerable.Empty<SelectListItem>());
    }
    public List<HttpPostedFileBase> Images { get; set; }

    public string AlbumID { get; set; }
    public SelectList Albums { get; set; }
}

public class Album
{
   public string AlbumID { get; set; }
   public string AlbumName { get; set; }
}

public class Repository
{
   public static List<Album> FetchAlbums()
   {
        List<Album> albums = new List<Album>
        {
            new Album(){ AlbumID = "Album1", AlbumName = "Album 1 desc"},
            new Album(){ AlbumID = "Album2", AlbumName = "Album 2 desc"}
        };
        return albums;
    }
}

and I call this UploadImageAlbum in a separate model called AdminViewModel as below:

public class AdminViewModel
{
    public UploadImageAlbum UIAModel { get; set; }
}

and in Controller I try to fill this model as below:

public PartialViewResult GetMediaUploadView()
{
   AdminViewModel model = new AdminViewModel();
   List<Album> albums = Repository.FetchAlbums();
   model.UIAModel.Albums = new SelectList(albums, "AlbumID", "AlbumName");//Error here
   //Object reference not set to an instance of the object
   return PartialView("_UploadMedia", model);
}

I also tried

public PartialViewResult GetMediaUploadView()
{
   AdminViewModel model = new AdminViewModel();
        List<Album> albums = new List<Album>(); //Creating as new List
        albums = Repository.FetchAlbums();//then assign
        model.UIAModel.Albums = new SelectList(albums, "AlbumID", "AlbumName");
        return PartialView("_UploadMedia", model);
}

But again, I am getting same error. No idea for what reason I am getting this error, even after initializing in model level as well as Controller level. Hope someone might have good knowledge on this. Below is the screen shot of the error I am getting.

Screenshot

Remote validation for kendowindow

I implement remote validation. It works for usual fields correctly, but if field is situated in kendowindow jquery validation does not work.

How can I solve this problem?

MVC drop dodown list onchange pass the selected value to the function in the controller and execute it

i am a new in using MVC3 Razor syntax and i have a view that containing a dropdownlist and i want when the user change the value of it , a function in the controller that take selected value as a parameter will be executed automatically. this is the code that i wrote in the view and i have a compilation error in that line at runtime:

 @Html.DropDownList("DONOR_BLOOD_GROUPE_ID", "--Select--", new {onchange="FilterdIndex(this.value)"}) 

"DONOR_BLOOD_GROUPE_ID" is in the viewBag and this is the function in the controller that i want to call .

public ViewResult FilterdIndex(int id)
        {
            var donor = db.DONOR.Include(d => d.BLOOD_GROUP);
            var DONOR_BLOOD_GROUPE_ID = from BG in db.BLOOD_GROUP
                            select new
                            {
                                BG.GROUP_ID,BG.GROUP_NAME,
                                Checked=(BG.GROUP_ID==id)
                            };
            ViewBag.DONOR_BLOOD_GROUPE_ID = DONOR_BLOOD_GROUPE_ID;
            return View(donor.ToList());
        }

Export to excel from kendo grid all data in controller

I am using kendo grid to show the data. Now i want to export to excel all the data of all the pages of grid. I have to do this in controller. I am using one export button where it does ajax call and calling FileResult method in controller. Below is my code:

$("#btnExport").click(function () {
       
        ExportReport();
       
    });

function ExportReport() {
        window.open('@Url.Action("ExportHotelUtilizationReport","DutyTravelRequestor")');
    }

and below is my controller File result method.

 public FileResult ExportHotelUtilizationReport()
        {
            //Session["HotelDetails"] = dModel.HotelUtilizationDetails;
            List<DutyTravelHotelUtilization> lstSeparation = null;
            MemoryStream output = new MemoryStream();
            try
            {

                if (Session["HotelUtilizationDetails"] != null)
                {

                    lstSeparation = (List<DutyTravelHotelUtilization>)HttpContext.Session["HotelUtilizationDetails"];
                    StreamWriter writer = new StreamWriter(output, Encoding.UTF8);
                    writer.Write("Duty Tavel ID,");
                    writer.Write("Staff Number,");
                    writer.Write("Staff Name,");
                    writer.Write("Grade ID,");
                    writer.Write("Category Name,");
                    writer.Write("City Code,");
                    writer.Write("City Name,");
                    writer.Write("Hotel Name,");
                    writer.Write("Total Cost,");
                    writer.WriteLine();
                    foreach (DutyTravelHotelUtilization lists in lstSeparation)
                    {

                        writer.Write(lists.DutyTravelId);
                        writer.Write(",");
                        writer.Write(lists.StaffNumber);
                        writer.Write(",");
                        writer.Write(lists.StaffName);
                        writer.Write(",");
                        writer.Write(lists.GradeId);
                        writer.Write(",");
                        writer.Write(lists.CategoryName);
                        writer.Write(",");
                        writer.Write(lists.CityCode);
                        writer.Write(",");
                        writer.Write(lists.CityName);
                        writer.Write(",");
                        writer.Write(lists.HotelName);
                        writer.Write(",");
                        writer.Write(lists.TotalCost);
                        writer.Write(",");
                        writer.WriteLine();


                    }
                    writer.Flush();
                    output.Position = 0;
                    Session["HotelUtilizationDetails"] = null;
                }
            }
            catch (Exception)
            {
            }

            return File(output.ToArray(), "application/vnd.ms-excel", "HotelUtilizationReport.xls");
        }
        
        

But value is not showing in correct format.

Call jquery function and send query to server by one click

@using (Ajax.BeginForm("Update", "User",}))
{     
            @Html.TextBoxFor(m => m.Name)   
           <input type="submit" name="update" value="Update" />
        }
}

Can I call jquery function if I click on submit?

mercredi 21 octobre 2015

Calling Jquery mobile function on View html to move Back and Next

I have two views files one is for product and second is for booking. Here is my script that I want to call between the view pages to go back and forth on pressing the back and next button. Please tell me how to do it. Thank you.

Script.js:

$(document).on('click', '.showNextPage', function() {
  $.mobile.navigate('#second', {
    transition: "slide"
  });
});

$(document).on('click', '.showPrevPage', function() {
  $.mobile.navigate("#index", {
    transition: "slide"
  });
});

Booking View Index.cshtml

@{
    Layout = ViewBag.Layout;
}
@{ViewGenerator vg = new ViewGenerator();
  CartInfo cartInfo = vg.GetBookingCartInfo();


    @section head{
        @Url.ScriptRender(BundleResources.BOOKIGN_SCRIPT)

        @{if (DffUtility.SalesChannelID == 2)
          {
            <!-- Google Tag Manager -->
            <script>
                var google_tag_params =
                {
                    hrental_id: '@cartInfo.ProdId',
                        hrental_pagetype: 'conversionintent',
                        hrental_startdate: '@cartInfo.StartDate.ToString("yyyy-MM-dd")',
                        hrental_enddate: '@cartInfo.EndDate.ToString("yyyy-MM-dd")',
                        hrental_totalvalue: '@cartInfo.TotalPrice'
                    }
            </script>

            <noscript>
                <iframe src='//www.googletagmanager.com/ns.html?id=GTM-NMVP7S' height='0' width='0' style='display: none; visibility: hidden'></iframe>
            </noscript>
            <script>(function (w, d, s, l, i) { w[l] = w[l] || []; w[l].push({ 'gtm.start': new Date().getTime(), event: 'gtm.js' }); var f = d.getElementsByTagName(s)[0], j = d.createElement(s), dl = l != 'dataLayer' ? '&l=' + l : ''; j.async = true; j.src = '//www.googletagmanager.com/gtm.js?id=' + i + dl; f.parentNode.insertBefore(j, f); })(window, document, 'script', 'dataLayer', 'GTM-NMVP7S');</script>
            <!-- End Google Tag Manager -->
          }
        }

        <!-- Advertiser 'Advantage Media Aps', Exclude user from segment 'Friferie 1. reg step Re-Targeting' -->
        <script type="text/javascript">
            var pixelSRCType = (("https:" == document.location.protocol) ? "https://" : "http://");
            var cId = '299f5c2b-2920-4888-acc7-37be7f8a9d28';
            var tName = 'basket';
            var pId = '@cartInfo.ProdId'; // Insert comma seperated string of productid/ids 
                var revenue = '';
                var orderId = '';
                var p1 = '';
                var p2 = '';
                var p3 = '';

                document.write("<iframe src='" + pixelSRCType + "http://ift.tt/1Gr7uV6" + cId + "&tName=" + tName + "&pId=" + pId + "&revenue=" + revenue + "&orderId=" + orderId + "&p1=" + p1 + "&p2=" + p2 + "&p3=" + p3 + "' allowtransparency='true' framespacing='0' frameborder='no' scrolling='no' width='0' height='0'></iframe>");
        </script>
        <!-- End of segment tag -->


    }

    <script type="text/javascript">
        var LoadCustomerInfo_Url, SaveBooking_Url, SendEmail_Url, CartInfo_Url, TENWEB_PATH, SeeMoreText, BOOKING_FORM, TellHome, Fax, PhoneHome, COAddress, City, Country,
            CUSTOMER_INFO, BASIC_MESSAGE, BASIC_RULE, IsPartialPayment;

        LoadCustomerInfo_Url = '@Html.Raw(string.Format("{0}/http://ift.tt/1Gr7t3B}", ConfigurationSettings.TENWEB_PATH, Request.QueryString))';
        SaveBooking_Url = '@Html.Raw(string.Format("{0}/http://ift.tt/1QVSGOE}", ConfigurationSettings.TENWEB_PATH, Request.QueryString))';
        SendEmail_Url = '@Html.Raw(string.Format("{0}/http://ift.tt/1Gr7tjP}", ConfigurationSettings.TENWEB_PATH, Request.QueryString))';
        CartInfo_Url = '@Html.Raw(string.Format("{0}/http://ift.tt/1QVSJtT}", ConfigurationSettings.TENWEB_PATH, Request.QueryString))';
        TENWEB_PATH = '@Html.Raw(ConfigurationSettings.TENWEB_PATH)';
        SeeMoreText = '@Html.Raw(DffUtility.GetGlobalResource("SeeMore"))';
        IsPartialPayment = '@cartInfo.IsPartialPayment.ToString().ToLower()';

        BASIC_MESSAGE = {
            FName: '@Html.Raw(DffUtility.GetGlobalResource("FirstNameErrorText"))',
            LName: '@Html.Raw(DffUtility.GetGlobalResource("LastNameErrorText"))',
            Email: {
                required: '@Html.Raw(DffUtility.GetGlobalResource("EmailErrorText"))',
                email: '@Html.Raw(DffUtility.GetGlobalResource("EnterYourEmailErrorText"))'
            },
            Email2: {
                required: '@Html.Raw(DffUtility.GetGlobalResource("ConfirmEmailErrorText"))',
                equalTo: "@Html.Raw(DffUtility.GetGlobalResource("ConfirmEmailNotMatchText"))",
                email: "@Html.Raw(DffUtility.GetGlobalResource("EnterConfirmEmailErrorText"))"
            },
            Address: '@Html.Raw(DffUtility.GetGlobalResource("AddressErrorText"))',
            PostNo: '@Html.Raw(DffUtility.GetGlobalResource("PostNoErrorText"))',
            MobileNo: '@Html.Raw(DffUtility.GetGlobalResource("MobileNoErrorText"))',
            ddlCancellationInsurance: '@Html.Raw(DffUtility.GetGlobalResource("CancellationInsuranceErrorText"))',
            ddlCardTypes: '@Html.Raw(DffUtility.GetGlobalResource("SelectCardType"))'
        }
    </script>
    <div class="bestilling">
        <form action="">
            <div class="bestilling_i">
                <h2>@Html.Raw(DffUtility.GetGlobalResource("OrderingOfHoliday"))</h2>
                <div class="bestilling-wrap pb17">
                    <div class="bestilling__col bestilling_Align">

                        <div class="row-sel">
                            <div class="inp">
                                <input type="email" placeholder="@Html.Raw(DffUtility.GetGlobalResource("Email"))" id="Email" name="Email" onchange="LoadCustomerInfo()">
                            </div>
                            <div class="inp">
                                <input type="text" placeholder="@Html.Raw(DffUtility.GetGlobalResource("FirstName"))" id="FName" name="FName">
                            </div>
                            <div class="inp">
                                <input type="text" placeholder="@Html.Raw(DffUtility.GetGlobalResource("Address"))" id="Address" name="Address">
                            </div>
                            <div class="inp">
                                <input type="number" pattern="[0-9]*" placeholder="@Html.Raw(DffUtility.GetGlobalResource("MobileNo"))" id="MobileNo" name="MobileNo">
                            </div>
                        </div>
                    </div>
                    <!--bestilling__col end-->
                    <div class="bestilling__col bestilling_Align">
                        <div class="row-sel">
                            <div class="inp">
                                <input type="email" placeholder="@Html.Raw(DffUtility.GetGlobalResource("ConfirmEmail"))" id="Email2" name="Email2">
                            </div>
                            <div class="inp">
                                <input type="text" placeholder="@Html.Raw(DffUtility.GetGlobalResource("LastName"))" id="LName" name="LName">
                            </div>
                            <div class="inp">
                                <input type="number" pattern="[0-9]*" placeholder="@Html.Raw(DffUtility.GetGlobalResource("PostNo"))"  id="PostNo" name="PostNo">
                            </div>
                            @*<div class="inp">
                                <input type="text" placeholder="@Html.Raw(DffUtility.GetGlobalResource("PromoCode"))"  id="PromoCode" name="PromoCode">
                            </div>*@
                        </div>
                    </div>
                    <!--bestilling__col end-->
                    <div class="clear-both"></div>
                </div>
                <div class="bestilling-wrap">
                    <h3>@Html.Raw(DffUtility.GetGlobalResource("DimensionsAndAcquisitions"))</h3>
                </div>
                @{if (cartInfo.IsCancellationInsuranceEnable)
                  {
                    <div class="bestilling-wrap pb19">

                        <div class="bestilling__col">
                            <i>@Html.Raw(string.Format(DffUtility.GetGlobalResource("AmendingAndCancellation"), cartInfo.CancellationInsurancePrice))</i>
                            <div class="row-sel">
                                <div class="inp">
                                    <select class="select-inp" tabindex="-1" title="" id="ddlCancellationInsurance" name="ddlCancellationInsurance" onchange="UpdateCartInfo()">
                                        <option value="0">@Html.Raw(DffUtility.GetGlobalResource("SelectIns"))</option>
                                        <option value="1">@Html.Raw(DffUtility.GetGlobalResource("YesPlease"))</option>
                                        <option value="2">@Html.Raw(DffUtility.GetGlobalResource("NoIns"))</option>
                                    </select>

                                </div>

                            </div>
                            <!--row-sel end-->
                        </div>
                        <!--bestilling__col end-->
                    </div>
                  }
                }
                <!--bestilling-wrap end-->
            </div>
            @*</form>*@

            <div class="bestilling__info">
                <div class="bestilling__info_i">
                    <p>
                        @cartInfo.DestinationText

                        <a class="btnMoreCartInfo" onclick="ShowMoreCartInfo()" href="javascript:void(0)">@Html.Raw(DffUtility.GetGlobalResource("SeeMore")) +</a>
                    </p>
                    <div class="more-text" id="MoreCartInfo">
                        <i>@Html.Raw(cartInfo.PaxAndDateInfoText)</i>
                        <div class="sub-total">
                            <div class="row">
                                <p><b>@cartInfo.AccomodationPriceText:</b> <i style="width: 70%;">@cartInfo.AccomodationDiscountText</i></p>
                                <span>@cartInfo.AccomodationPriceValue<br />
                                    <i>@cartInfo.AccomodationDiscountValue</i></span>
                            </div>
                            @{if (cartInfo.MandatoryProdObjs != null)
                              {
                                  foreach (MandatoryProdObjs mpo in cartInfo.MandatoryProdObjs)
                                  {
                                <div class="row">
                                    <p>@mpo.Caption:</p>
                                    <span>@mpo.Price</span>
                                </div>
                                  }
                              }
                            }
                            @{if (!string.IsNullOrEmpty(cartInfo.CleaningValue))
                              {
                                <div class="row">
                                    <p>@cartInfo.CleaningText:</p>
                                    <span>@cartInfo.CleaningValue</span>
                                </div>
                              }
                            }
                            @{if (cartInfo.IsCancellationInsuranceEnable)
                              {
                                <div class="row">
                                    <p>@cartInfo.CancellationInsurance:</p>
                                    <span class="CancellationInsurancePrice">@cartInfo.CancellationInsuranceValue</span>
                                </div>
                              }
                            }
                        </div>
                    </div>
                </div>
                <div class="total">
                    <p>@cartInfo.TotalPriceText:<a class="btnMoreTotalPrice" onclick="ShowMoreTotalPrice()" href="javascript:void(0)">@Html.Raw(DffUtility.GetGlobalResource("SeeMore")) +</a></p>
                    <span class="TotalPrice">@cartInfo.TotalPriceValue</span>
                    <div class="more-text" id="MoreTotalPrice"><i>@Html.Raw(DffUtility.GetGlobalResource("BookingFeeInclusive"))</i></div>
                </div>




            </div>

            @{ if (cartInfo.IsPaymentEnable)
               {
                   string fullPaymentCheck = "checked";
                   string partialPaymentCheck = "";
                   string totalPaymentDisplay = "none";
                   if (cartInfo.IsPartialPayment)
                   {
                       fullPaymentCheck = "";
                       partialPaymentCheck = "checked";
                       totalPaymentDisplay = "block";
                   }
                <div class="bestilling__info" style="background: #fff;">
                    <div class="bestilling__info_i" style="padding-bottom: 0px;">
                        <p>
                            @cartInfo.ChoosePaymentMethod

                            <a class="btnMorePaymentInfo" style="padding-bottom: 5px;" onclick="ShowMorePaymentInfo()" href="javascript:void(0)">@Html.Raw(DffUtility.GetGlobalResource("SeeMore")) -</a>
                        </p>
                        <div class="more-text payment-info" id="MorePaymentInfo" style="display: block">
                            @{ if (cartInfo.ChkFullPayment && cartInfo.ChkInstallmentPayment)
                               {
                                <span>
                                    <input type="checkbox" id="chkFullPayment" name="chkFullPayment" @fullPaymentCheck onchange="FullPayment()">
                                    <b style="vertical-align: super;" class="FullPaymentText">@cartInfo.FullPaymentText</b><br>
                                    <input type="checkbox" id="chkFirstPayment" name="chkFirstPayment" onchange="FirstPayment()" @partialPaymentCheck>
                                    <b style="vertical-align: super;" class="InstallmentPaymentText">@cartInfo.InstallmentPaymentText</b>
                                </span>
                               }
                            }
                            <div class="sub-total">

                                <div class="row pnlTotalPrice" style="display: @totalPaymentDisplay;">
                                    <p>@cartInfo.TotalPriceText:</p>
                                    <span class="TotalPrice">@cartInfo.TotalPriceValue</span>
                                </div>
                                <div class="row">
                                    <p>@cartInfo.PaymentPriceText:</p>
                                    <span class="PaymentPriceValue">@cartInfo.PaymentPriceValue</span>
                                </div>
                                <div class="row">
                                    <p class="CardFeeText">@cartInfo.CardFeeText:</p>
                                    <span class="CardFeeValue">@cartInfo.CardFeeValue</span>
                                </div>
                                <div class="row">
                                    <p class="FirstPaymentText">@cartInfo.FirstPaymentText:</p>
                                    <span class="FirstPaymentValue">@cartInfo.FirstPaymentValue</span>
                                </div>

                            </div>
                            <div style="padding-top: 10px;">
                                <p>
                                    @cartInfo.ChoosePayment:
                                </p>

                                <div class="row-sel">
                                    <div class="inp">
                                        <select class="select-inp" tabindex="-1" title="" id="ddlCardTypes" name="ddlCardTypes" onchange="UpdateCartInfo()">
                                            @{ foreach (CardTypes type in cartInfo.CardTypes)
                                               {
                                                <option value="@type.Value">@type.Text</option>
                                               }
                                            }
                                        </select>

                                    </div>

                                </div>
                            </div>
                        </div>
                    </div>
                </div>
               }
            }

            <div class="bestilling__info" style="padding: 14px 0px;">
                <div class="bestilling__info_btn">
                    <a class="btn btn_green" onclick="SaveBooking()" id="btnSave" href='javascript:void(0)'>@Html.Raw(DffUtility.GetGlobalResource("Book"))</a>
                </div>
            </div>
        </form>
        <!--bestilling__info end-->
    </div>
}
<div class="Progress_Layout" style="display: none;">
    <div class="Progress_Content">
        <div>
            <img src="@Url.FilePath(FileTypes.IMAGES, "loader", "10271456A2B3")" style="vertical-align: middle" alt="" />
        </div>
        <div class="Progress_Text">
            @DffUtility.GetGlobalResource("pleaseWait")
        </div>
    </div>
</div>







 <div data-role="page" id="index" data-theme="a" >
            <div data-role="header">
                <h3>
                    First Page
                </h3>




                <a class="ui-btn-right showNextPage">Next</a>
            </div>

            <div data-role="content">


                <p>1st List Example:</p>
<ol>
<li>HTML Examples</li>
<li>HTML Tutorial</li>
<li>HTML Codes</li>
<li>and much more!</li>
</ol>
            </div>

            <div data-role="footer" data-position="fixed">

            </div>
        </div> 
        <div data-role="page" id="second" data-theme="a" >
            <div data-role="header">
                <h3>
                    Second Page
                </h3>



                <a class="ui-btn-left showPrevPage">Back</a>
            </div>

            <div data-role="content">
                 <p>Image  Example:</p>
<p>Second List Example:</p>
<ol>
<li>HTML Examples</li>
<li>HTML Tutorial</li>
<li>HTML Codes</li>
<li>and much more!</li>
</ol>

            </div>

            <div data-role="footer" data-position="fixed">

            </div>
        </div>

Product View:

@{
    Layout = ViewBag.Layout;
}
<script type="text/javascript">

    PAGE_TYPE = @DffUtility.PageType,
    BASIC_PARA = '@(Html.Raw(DffUtility.Basic_QueryString))'



</script>

@section head{
    @Html.Raw(ViewBag.SEARCH_HEAD)
    @Html.Raw(ViewBag.SEARCH_SCRIPT)

    @Url.ScriptRender(BundleResources.WOWSLIDER_SCRIPT)
    @Url.ScriptRender(BundleResources.SOCIAL_SCRIPT)
}

@section header{
    @Html.Raw(ViewBag.SEARCH_HTML)
    @Html.Partial("PriceCalculation")
}
@Html.Raw(ViewBag.HTML)

@section footer{
    @Url.CssRender(BundleResources.WOWSLIDER_CSS)
}

Layout.cshtml:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>@Html.Raw(ViewBag.Title)</title>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
    <meta id="descriptionTag" name="description" content="@MvcHtmlString.Create(ViewBag.Description)" />
    <meta name="ROBOTS" content="NOINDEX, NOFOLLOW" />
    <meta name="ROBOTS" content="NOHTMLINDEX" />
    <link href="@Url.FilePath(FileTypes.IMAGES, "favicon", "C3AC16EE6772")" rel="shortcut icon" type="image/x-icon" />

    <style>
         @{ string  basefontpath = ConfigurationSettings.HOST + Url.Content("~/Resources/") + "fonts/";
        }
        @@font-face { font-family: 'TradeGothicLTStdBold'; src: url("@(basefontpath + "TradeGothicLTStdBold.eot")"); src: url("@(basefontpath + "TradeGothicLTStdBold.eot")") format("embedded-opentype"), url("@(basefontpath + "TradeGothicLTStdBold.woff2")") format("woff2"), url("@(basefontpath + "TradeGothicLTStdBold.woff")") format("woff"), url("@(basefontpath + "TradeGothicLTStdBold.ttf")") format("truetype"), url("@(basefontpath + "TradeGothicLTStdBold.svg#TradeGothicLTStdBold")") format("svg"); }
        @@font-face { font-family: 'ITCAvantGardeStdMd'; src: url("@(basefontpath + "ITCAvantGardeStdMd.eot")"); src: url("@(basefontpath + "ITCAvantGardeStdMd.eot")") format("embedded-opentype"), url("@(basefontpath + "ITCAvantGardeStdMd.woff2")") format("woff2"), url("@(basefontpath + "ITCAvantGardeStdMd.woff")") format("woff"), url("@(basefontpath + "ITCAvantGardeStdMd.ttf")") format("truetype"), url("@(basefontpath + "ITCAvantGardeStdMd.svg#ITCAvantGardeStdMd")") format("svg"); }

        @@font-face {font-family: 'Droid Sans';font-style: normal;font-weight: 400;src: local('Droid Sans'), local('DroidSans'), url("@(basefontpath + "s-BiyweUPV0v-yRb-cjciL3hpw3pgy2gAi-Ip7WPMi0.woff")") format('woff');}
        @@font-face {font-family: 'Droid Sans';font-style: normal;font-weight: 700;src: local('Droid Sans Bold'), local('DroidSans-Bold'), url("@(basefontpath + "EFpQQyG9GqCrobXxL-KRMXbFhgvWbfSbdVg11QabG8w.woff")") format('woff');
        @@font-face {font-family: 'Open Sans';font-style: normal;font-weight: 400;src: local('Open Sans'), local('OpenSans'), url("@(basefontpath + "cJZKeOuBrn4kERxqtaUH3bO3LdcAZYWl9Si6vvxL-qU.woff")") format('woff');}
        @@font-face {font-family: 'Open Sans';font-style: normal;font-weight: 700;src: local('Open Sans Bold'), local('OpenSans-Bold'), url("@(basefontpath + "k3k702ZOKiLJc3WVjuplzKRDOzjiPcYnFooOUGCOsRk.woff")") format('woff');}
        @@font-face {font-family: 'Open Sans';font-style: normal;font-weight: 600;src: local('Open Sans Semibold'), local('OpenSans-Semibold'), url("@(basefontpath + "MTP_ySUJH_bn48VBG8sNSqRDOzjiPcYnFooOUGCOsRk.woff")") format('woff');}
}
    </style>
    @{
        @Url.ScriptRender(BundleResources.BASIC_SCRIPT)
        @Url.CssRender(BundleResources.BASIC_CSS)
    }
    @RenderSection("head", required: false)


    <script type="text/javascript">

        src = "http://ift.tt/1toXtPU"
        src = "http://ift.tt/18XrlsC"
      $(document).on('click', '.showNextPage', function() {
        $.mobile.navigate('#second', {
            transition: "slide"
        });
    });

    $(document).on('click', '.showPrevPage', function() {
        $.mobile.navigate("#index", {
            transition: "slide"
        });
    });
        </script>
</head>
<body>
    <header>
        <div class="fri-col-sm-1 ">
            <a class="arr-prev" href="#">&nbsp;</a>
        </div>
        <div class="fri-col-sm-7 ">
            <a class="logo" href="@ViewBag.Site">
                <img src="@Url.FilePath(FileTypes.IMAGES, "logo", "AC9A5300E0D9")" alt="friferie" /></a>
        </div>
        <div class="fri-col-sm-1 ">
           @*@(Html.RenderControl<Menu>("~/Menu/Menu.ascx", x => { x.MENU_NAV = SharePointServiceHelper.GetAllNavigationTerms(); x.MENU_ISMOBILE = DffUtility.IsMobile; x.MENU_PATH = Url.Content("~"); x.MENU_CSS = Url.FilePath(FileTypes.CSS, "Menu", "C7FC02E3E231"); x.MENU_JS = Url.FilePath(FileTypes.JS, "menu", "FAA6A2464B43"); x.MENU_ICON = Url.FilePath(FileTypes.IMAGES, "menu", "4A01DD1145F6"); x.MENU_EXTRACLASS = "menu-icon"; }))*@
        </div>
        <div class="clear-both"></div>
         @RenderSection("header", required: false)
    </header>
    <div class="content">

        <div class="ferie-home">
            @RenderBody()
        </div>
        @*@Html.Raw(ViewBag.Footer)*@

    </div>

    @RenderSection("footer", required: false)
</body>
</html>

how to give multiple routes in route.config file

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


        routes.MapRoute(
           name: "Letter",
           url: "{Home}/{Letter}/{ListId}",
           defaults: new { controller = "Home", action = "Letter", ListId=1}                               
       );

        routes.MapRoute(
      name: "words",
      url: "{Home}/{words}/{WListId}",
      defaults: new { controller = "Home", action = "words", WListId ="w1"   }
  );

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

        }





  cshtml:-
   @Html.ActionLink("Home", "Index", "Home")

   @Html.ActionLink("Letter", "Letter/1", "Home")
    @Html.ActionLink("Words", "words/w1", "Home")

i am doing this in route.config and .cshtml respectively but every time it redirect me to the letter page even when i click on "words" or "home". when i click words or home it changes the url but does not change the view. can any one suggest how to give multiples route in route.config file? whats wrong with this code ?

Left Menu Has Hug Gap if Page Is Resized

I have an issue with my application where the left menu has a huge gap when the page is resized. I've played around with the css file, but I a have not had success with it. You help will be greatly appreciated.

CSS Class:

.leftMenu {
    width: 210px;
    height: 100%;
    position: fixed;
    background-color: #0083AA;
    -webkit-transition: all .3s ease-in-out;
    -moz-transition: all .3s ease-in-out;
    -o-transition: all .3s ease-in-out;
    transition: all .3s ease-in-out;
    z-index: 100;
    margin-left:-25px;
}

Screeshots:

enter image description here

enter image description here

Html.Ation InsufficientExecutionStackException

Can not figure out what is wrong with it. There are two views. TabOne that render another view TabTwo with help of @Html.Action("Index", new { some params }) and TabTwo that render itself with different model with help of same @Html.Action("IndexPortlet", new { some params })

It started fail due migration from MVC3 to MVC4 with exception:

   at System.Runtime.CompilerServices.RuntimeHelpers.EnsureSufficientExecutionStack()
   at System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
   at System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
   at System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
   at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
   at System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout)
   at System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag)
   at System.Web.Mvc.Controller.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
   at System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout)
   at System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
   at System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout)
   at System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag)
   at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
   at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BegavinProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
   at System.Web.Mvc.Async.AsyncResultWrapper.Begin[TResult](AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate`1 endDelegate, Object tag, Int32 timeout)
   at System.Web.Mvc.Async.AsyncResultWrapper.Begin(AsyncCallback callback, Object state, BeginInvokeDelegate beginDelegate, EndInvokeDelegate endDelegate, Object tag)
   at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
   at System.Web.Mvc.HttpHandlerUtil.ServerExecuteHttpHandlerWrapper.Wrap[TResult](Func`1 func)
   at System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage, VirtualPath path, VirtualPath filePath, String physPath, Exception error, String queryStringOverride)
   at System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm, Boolean setPreviousPage)
   at System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler, TextWriter writer, Boolean preserveForm)
   at System.Web.Mvc.Html.ChildActionExtensions.ActionHelper(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues, TextWriter textWriter)
   at System.Web.Mvc.Html.ChildActionExtensions.RenderAction(HtmlHelper htmlHelper, String actionName, String controllerName, RouteValueDictionary routeValues)
   at SandBox.CorePolicy.V1_5.Views.Bootstrap.Edit.Views_Quotation_Products_CorePolicy_1_5_Edit_Bootstrap_TabDetails_cshtml.Execute() in c:\longpathtoview\TabTwo.cshtml:line 123
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
   at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
   at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
   at RazorGenerator.Mvc.PrecompiledMvcView.Render(ViewContext viewContext, TextWriter writer)
   at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
   at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
   at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)

While debugging TabTwo does not call Html.Action more that one time (whatever it does not hit breakpoint more than once). I've already google for this also stackoverflow site but everything what i've found is that mvc4 async controller do sync child method execution for Html.Action that can be issue in some cases. Still it doesn't help

Please, could you advise with any help?

IEnumerable

I'm having following controller

        [HttpGet]
        [ValidateInput(false)]     
        public ActionResult Create_Template(IEnumerable<ProductsPropertiesVM> model)
        {
            // new you have access to all the ID's of the selected items, for example
            IEnumerable<int> selectedIDs = model.Where(x => x.IsChecked).Select(x => x.Property_ID);

            return View(selectedIDs);
        }

I want bind that IEnumerable<int> selectedIDs data values to view

Once I run this on debug mode normally those selectedIDs appear like this

enter image description here

So I want to pass those IEnumerable data set to view first and then show or hide div sections according to that values on viewpage

if I able to to bind data to view, I have palnned to show or hide div sections like below (appreciate your suggestions)

 @{
        ViewBag.Title = "Create Templat";
    }
    <!DOCTYPE html>
    <html>
    <head>
        <title>Create a Templat</title>
    </head>
    <body>

        <div id="header"> .... </div>

        <div id="nav"> .... </div>

        <div id="section"> .... </div>

        <div id="footer"> .... </div>


    </body>
    </html>

    @section Scripts {
        @Scripts.Render("~/bundles/jqueryval")
        @Scripts.Render("~/bundles/jqueryui")

    <script type="text/javascript">


            $(document).ready(function () {

                //using for loop read the array values index 0  to end:

                for(i=0;i<array.length();i++){

                if(array has value 1) $("#header").show()
                else $(#header").hide();

                if(array has value 2) $("#nav").show()
                else $("#nav").hide();

                if(array has value 3) $("#section").show()
                else $("#section").hide();

                .........

                }
});   

    </script> 
    }

So I'm looking for good way to do this

mardi 20 octobre 2015

Jquery ad-gallery plugin: Load photos on demand and load rest on next/previous button

We are working on ASP.Net MVC web application. The application has implemented Jquery ad-gallery slideshow plugin. It is loading all images in one go whether the number of images is more than 2k. Can this plugin be modified to load photos on demand. For eg: Load 5 images initially. When user clicks next/previous button, then load next 5 images.

The images are stored in database. So each time,a connection will be made to database.

Let me know if it is possible with ad-gallery plugin or is there any better approach.

Fill nulls to six-digit format

@Html.DisplayFor(m => m.id)

id is int property How I can display this value as six-digit format. For example, if id = 1. I want to display 000001, if id = 123 - 000123 etc.

lundi 19 octobre 2015

Error using Server.Execute outside of controller

I am trying to run Server.Execute outside of the controller from an external function. I have tried passing numerous types of objects trying to get this to work, but each time I get an error saying Error: Error executing child request for [url]

This is how my code looks inside of the controller:

public async Task<ActionResult> Exec(){
    var http = HttpContext; //<- doesn't work
    http = HttpContext.ApplicationInstance.Context; //<- doesn't work

    execMethodAsync(http);
}

Then in another class the code is:

public async Task execMethodAsync(HttpContext context){
   context.Server.Execute("/myurl"); // <-- Throws error
}

I have tried passing a number of object types to this method but still get this error.

I tried passing HttpContext, HttpContext.CurrentHandler, ControllerContext.HttpContext and even some other ones, but still get this error. It seems nearly impossible to run Server.Execute() outside of the controller. Can someone please help with executing Server.Execute outside of the controller?

How to save the contents of a currently opened webpage in browser on button click event?

How to save the contents of a currently opened webpage in browser after performing some operations on that page, on button click event using c#?

Here all the visible contents on the page should get saved as a .pdf file or as an image file(.jpg, or, .png).

dimanche 18 octobre 2015

Load latest record and remove cache

I have an Action method like below..

[HttpGet, Route("All-Users"), OutputCache(Duration = 86400)]
public async Task<ActionResult> AllUsers()
{
    var list = await _user.GetUsersList();
    return View(list);
}

I have another Action method that saves the User. here the problem is that when I save the user..it still shows cache Page content. So this means newly added users are not appearing.

Kindly suggest how can i get rid of this issue.

I checked on Google that Cache can cleared as shown in this page

Question: Will it clear cache for all pages or for above action method only ?

Caching in Web API

I installed below Package in Web API.

Install-Package Strathweb.CacheOutput.WebApi2

I have an Action Method in Web API

[Route("api/v1/AllRoles"), HttpGet]
[CacheOutput(ClientTimeSpan = 100, ServerTimeSpan = 0)]
public async Task<IHttpActionResult> GetAll()
{
    var result = await _role.RolesList();
    return Ok(new { ErrorMessage = result.Key, result = result.Value });
}

So, Request goes to Database when ServerTimeSpan = 0 When I set ServerTimeSpan = 100 ...it does not go to Database.

I read from Google that ServerTimeSpan = 0 means Client Side Caching will be enabled and Server Side will be disabled.

I have a couple of Questions that I searched on Google but could not found it.

  1. May I ask if the Intervals are in milliseconds that are mentioned in Caching Attribute ?
  2. May I ask why request to goes to database when Client Side Caching is enabled ?

samedi 17 octobre 2015

Controller ViewBag.data in _Laoyut.cshtml

I have a Controller and I want to send ViewBag data in Controller at _Layout.cshtml.

Example:

_Layout.cshtml:

<!DOCTYPE html>
<html>
    <head>
        <title>@ViewBag.username Blog Site</title>
    </head>
    <body>
        <h1>Welcome, @ViewBag.username</h1>
        @RenderBody()
    </body>
</html>

MainController.cs

public class MainController : Controller
{
    public ActionResult Index()
    {
        if (HttpContext.Session["user"] != null)
        {
            var user = (tbl_user)HttpContext.Session["user"];
            ViewBag.username = user.username;
            ViewBag.testdata = "hellooo!";
        }
        return View();
    }
}

Index.cshtml:

<label>Index Page</label>
<br/>
<label>@ViewBag.testdata</label>

Result:

Welcome,

Index Page
hellooo!

vendredi 16 octobre 2015

Errors in MVC Application

I am new to MVC. I have reinstalled my visual studio ultimate 2010. Now when I am creating a new project, its showing lot of erros,

See the screenshot, How to solve this, Please help ?

enter image description here

How to receive associative array data with 'FormCollection' in ASP.NET MVC3

I have following data to send ajax call to the controller action:

  var data = {
      "PersonalInfo": [
        {      
          "FirstName": "Leonel",
          "LastName": "Messi"     
        },
        {
           "FirstName": "Cristiano",
          "LastName": "Ronaldo" 
        }
      ]
    };

Ajax call method:

$.ajax({
        url: "/Home/Create",
        type: "POST",
        dataType: "json",
        data: (JSON.parse(data)).PersonalInfo,
        success: function (response) {    }                       
    });

Controller Action:

public ActionResult Create(FormCollection formCollection)
{
    base.Create(formCollection);
}

In server side, I need array/list of FormCollection. e.g->

 formCollection[0] = {      
              "FirstName": "Leonel",
              "LastName": "Messi"     
            }


formCollection[1] = {      
                  "FirstName": "Leonel",
                  "LastName": "Messi"     
                }

Or something like this:

public ActionResult Create(List<FormCollection> formCollection)
    {

    }

But it is not possible, are there any alternative for this context?

Search functionality in C#

In my C# app I am showing order list in a table. The url to that page is

/Organization/Orders/id

id in this case is organization id. My controller looks like this

    [HttpGet]
    public ActionResult Orders(String id)
    {
        Organization org = Organization.Get(id);
        List<Order> orders = new List<Order>();

        foreach (Order order in org.GetOrders(50))
        {
            orders.Add(order);
        }

        ViewBag.Orders = orders;
        return View(org);
    }

Now I am trying to implement a search functionality in there. In the view I have a search form going on. When the user hits the search button I take him to this controller

    [HttpPost]
    public ActionResult Orders(String orgId, String locationName)
    {
        Organization org = Organization.Get(orgId);
        List<Order> orders = new List<Order>();

        foreach (Order order in org.GetOrders(50).Where(i => i.GetLocation().FriendlyName.Contains(locationName)))
        {
            orders.Add(order);
        }

        ViewBag.Orders = orders;
        return View(org);
    }

The issue with this approach is that, if the user search for a particular location name it will take him to the Post method. It will work fine but lets assume that the user refreshes the browser it will still show the searched content rather than the reset the search.

I understand it is because I am in the post method and in the post parameters I would have locationName.

So, is there any other good way to do implement search?

jeudi 15 octobre 2015

Day and month reverse during MVC model binding

I have a strange problem seems to only happens in the test W2k12 server for my ASP MVC3 app.

My development environment is MVC3/.NET4.0/Win7/VS2010. The deployment server is W2k12 running .NET 4.5

In my model, my datetime fields are generally defined as:

[DisplayName("From (dd/mm/yyyy)")]
[Required]
[DataType(DataType.Date)]
public DateTime? InputDateTime { get; set; }

In my view, it just render out the date as string within a text box (i.e. without datepicker)

In my development box (Win7 professional), if I type day and month only (for example: dd/mm), and then click the Save/Submit button, it calls the JQuery .serialize() method and pass on to the controller's AJAX method. It maps to date field correctly in the dd/mm/yyyy format (and add the current year automatically). It also saves to DB as a date field no problem.

It is important to note that the form data is serialized and not passed as Json string (not stringified), using $.ajax (jQuery 1.7.x)

If I type 'dd/mm/yyyy' in the text box, it also saves correctly.

However, my problem starts after the program has been deployed to the W2K12 server (running under .NET 4.5):

if I type only dd/mm (e.g. 10/04), the day and month swap and saves as mm/dd (plus the current year, thus mm/dd/yyyy). The 'swapping' does not occur on the jQyery.serializer but it only passes on to the MVC controller as a string.

If I type the full dd/mm/yyyy, the month and date don't swap

I check the regional and date format (short/long date) on the W2k12 they all seem OK (Australia region, dd/mm/yyyy format) and identical to my W7 box.

Can someone shed some lights on that? Please ask if you require more information.

p.s. the following is already in web.config file:

<globalization requestEncoding="utf-8" responseEncoding="utf-8" culture="en-AU" uiCulture="en-AU" />

What steps are required to change Forms Authentication over to Windows Authentication in an MVC3 web application?

I am working on a legacy MVC3 application which uses Forms authentication and SQLMembership Provider for authorizing user access. It has the folowing configuration:

<authentication mode="Forms">
  <forms loginUrl="~/Account/Login" timeout="2880" />
</authentication>
<membership>
  <providers>
    <clear />
    <add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="true" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="true" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="3" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/TimeSheets" passwordFormat="Clear" />
  </providers>
</membership>
<profile inherits="Timesheets.Services.UserProfile">
  <providers>
    <clear />
    <add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/TimeSheets" />
  </providers>
</profile>
<roleManager enabled="true">
  <providers>
    <clear />
    <add name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" connectionStringName="ApplicationServices" applicationName="/TimeSheets" />
    <add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/TimeSheets" />
  </providers>
</roleManager>

If I create a new MVC application using Windows Authentication this configuration seems to be replaced with configuration like this:

<authentication mode="Windows" />
<authorization>
  <deny users="?" />
</authorization>

I have tried just changing the configuration of the legacy MVC site to use this new authentication mode, but this fails to authenticate (I get an Error message "401.2.: Unauthorized: Logon failed due to server configuration.")

However the new web project runs and authenticates correctly (so it's not an AD or local permissions issue)

I had thought to try just putting all the legacy code into the new project but it is rather large and complex and getting everything lined up again in the new site could be very time consuming.

I'm hoping that changing the Auth model should be simpler and less intrusive - But what additional steps would I need to perform to configure the legacy site for Windows Authentication?

Format entity values before comparison in lambda expression

Is there a way, I can format the string values before comparing with input arguments? For example: I need to format "x.SerialNumberInput" before comparing it with "serialNumberFinal" session.QueryOver().Where(x => (formattedNumber(x.SerialNumberInput) == serialNumberFinal)).List();

I have also defined the formattedNumber method in the class. There is no compile time error but at run time, it says Unrecognised method call in epression value(Test).formattedNumber(x.SerialNumberInput)

Method body

protected string formattedGIBNumber(string serialNumber) { if (serialNumber.StartsWith("B") && serialNumber.Contains('-')) { return serialNumber.Split('-')[0]; } else { return serialNumber; } }

Bad request(400) in OAuthWebSecurity.VerifyAuthentication authcofig facebook login

I am creating a social media login from my site and i have created a sample project to check it but the ExternalLoginCallback action not working properly and

`   AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));`

Throws exception as

The remote server returned an error: (400) Bad Request.

the stack trace is

Source Error:


Line 218:        public ActionResult ExternalLoginCallback(string returnUrl)
Line 219:        {
Line 220:             AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
Line 221:           // AuthenticationResult result = null;// = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
Line 222:            string code = Request.QueryString["code"];


Source File: e:\Test\MvcApplication2\MvcApplication2\Controllers\AccountController.cs    Line: 220

Stack Trace:


[WebException: The remote server returned an error: (400) Bad Request.]
   System.Net.WebClient.DownloadDataInternal(Uri address, WebRequest& request) +283
   System.Net.WebClient.DownloadString(Uri address) +100
   DotNetOpenAuth.AspNet.Clients.FacebookClient.QueryAccessToken(Uri returnUrl, String authorizationCode) +350
   DotNetOpenAuth.AspNet.Clients.OAuth2Client.VerifyAuthentication(HttpContextBase context, Uri returnPageUrl) +202
   DotNetOpenAuth.AspNet.OpenAuthSecurityManager.VerifyAuthentication(String returnUrl) +411
   Microsoft.Web.WebPages.OAuth.OAuthWebSecurity.VerifyAuthenticationCore(HttpContextBase context, String returnUrl) +189
   Microsoft.Web.WebPages.OAuth.OAuthWebSecurity.VerifyAuthentication(String returnUrl) +139
   MvcApplication2.Controllers.AccountController.ExternalLoginCallback(String returnUrl) in e:\Test\MvcApplication2\MvcApplication2\Controllers\AccountController.cs:220
   lambda_method(Closure , ControllerBase , Object[] ) +180
   System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +211
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
   System.Web.Mvc.Async.<>c__DisplayClass42.<BeginInvokeSynchronousActionMethod>b__41() +28
   System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +48
   System.Web.Mvc.Async.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33() +57
   System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +223
   System.Web.Mvc.Async.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49() +223
   System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__36(IAsyncResult asyncResult) +10
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +48
   System.Web.Mvc.Async.<>c__DisplayClass2a.<BeginInvokeAction>b__20() +24
   System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult) +102
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +57
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +43
   System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult) +14
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +57
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +47
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
   System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult) +25
   System.Web.Mvc.Async.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar) +23
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +47
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9514812
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

The url return from facebook is

http://localhost:54474/Account/ExternalLoginCallback?__provider__=facebook&__sid__=e07b65643de449b6b61fccabcba9dcfd&code=AQCY7rTkkrOvLJU9qAk4l-FK2UNgNqetQPof27DxEgsPcEYL_xoafxd50x_YYWcifQ86qBm8PZnipbQOe3f6cLjrRFCqEnqwHKb4QAEuFHeVU0iAhhWLkjAJ_uWVtA1GsFxk0RkXIsFv3qgPuD9Yzgw2LU44M3LpIxEKnrkvqa7huFSr3iPxvpNU5RWDwEpxBa2946CiLXfOjLpSn6D1ImSG5rs8zP8g_yuIcMgfJR8biyuv2sTpEIwkxb7vuflWrlbPedDla8KtucJEZcK5ZFeZXyDOE153TeTLWdCMsH74ii5JObawDkH9eGbwhoO4y34#_=_

My authconfig code is

  OAuthWebSecurity.RegisterFacebookClient(
                appId: ConfigurationManager.AppSettings["FBAPPID"],
                appSecret: ConfigurationManager.AppSettings["FBAPPSECRET"]);

I have been stuck this problem for hours any one please help