Wednesday 18 January 2017

Print DataTable To CSV in MVC C#


Code to print simple data table values to csv.



public ActionResult PrintDataToCsv()
        {

            string StartDate = Request.Params["StartDateP"] == null ? "" : Request.Params["StartDateP"].ToString();
            string EndDate = Request.Params["EndDateP"] == null ? "" : Request.Params["EndDateP"].ToString();

            string PageName = Request.Params["PageName"] == null ? "" : Request.Params["PageName"].ToString();

            String EnddateConverted = "";
            String StardateConverted = "";
            if (StartDate != "")
            {
                StardateConverted = Convert.ToDateTime(StartDate.ToString()).ToString("MM/dd/yyyy");
            }
            else
            {
                StardateConverted = StartDate;
            }
            if (EndDate != "")
            {
                EnddateConverted = Convert.ToDateTime(EndDate.ToString()).ToString("MM/dd/yyyy");
            }
            else
            {
                EnddateConverted = EndDate;
            }
       
            System.Web.UI.WebControls.GridView gv = new System.Web.UI.WebControls.GridView();

//Here is my datatable which return from procedures.

            DataTable dt = GetAllDataToPintToCsv(StardateConverted, EnddateConverted,PageName);

            StringWriter sw = new StringWriter();
           //Header Part
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                sw.Write(dt.Columns[i]);
                if (i < dt.Columns.Count - 1)
                {
                    sw.Write(",");
                }
            }
            sw.Write(sw.NewLine);

//Header Data

            foreach (DataRow dr in dt.Rows)
            {
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    if (!Convert.IsDBNull(dr[i]))
                    {
                        string value = dr[i].ToString();
                        if (value.Contains(','))
                        {
                            value = String.Format("\"{0}\"", value);
                            sw.Write(value);
                        }
                        else
                        {
                            sw.Write(dr[i].ToString());
                        }
                    }
                    if (i < dt.Columns.Count - 1)
                    {
                        sw.Write(",");
                    }
                }
                sw.Write(sw.NewLine);
            }
            sw.Close();

         

            gv.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=myfilename.csv");
            Response.ContentType = "text/csv";
            Response.Charset = "";

            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();


            return RedirectToAction("/account/PrintDataToCsv");

        }




   <form name="Printing" id="Printing" action="/account/PrintDataToCsv" >

              <input type="hidden" id="StartDate" name="StartDateP"  value="@StartDate">
               <input type="hidden" id="EndDate" name="EndDateP" value="@EndDate">
              <input type="hidden" name="PageName" id="searchdata"  value="@PageName" />
           
              <button type="submit" class="btn btn-success  btn-export" title="Print">Export</button>
     </form>

Javascript Design Pattern



Hi, Today we will learn to write a very basic modular pattern of JavaScript. But before going ahead we should first familiar with what design pattern actually do.
Design pattern represents that code is written by experienced object oriented software developers.
So as we write daily multiple codes, and if we did not organised our code then day by day it goes complex. We can prevent from being a irritated developers by organizing our code.

We are going to learn a very basic of modular pattern that is commonly used by experience developers.

Suppose we have to do multiple calculation and for this we have to write too many functions and if we organized it in patterns it become readable. Here my calculation function will store all calculation functions and based on its default calling on calculation function load.

Syntax:-       var myFunction = function(){
                                    var fun1 = function(){}
                                     var fun2 = function(){}
                      return{ one: fun1,two:fun2}
                    };



var MyCalculation = function () {

//Here we can define our private variable that we can access in functions.

var addOperation = function (a, b) {
        alert(a + b);
    };
var subtrOperation = function (a, b) {
        alert(a - b);
    }


return {

 //Here you can define public accessibility for this Complete function.  
//Note in our whole function this is only entry and exist which will returned.

        add: addOperation ,
        subtract: subtrOperation ,
        multiple: function (a, b) {
            alert(a * b);
        }
    }
};

Now calling part 

//For using our modular function we first need to create an instance for our function.

var calculation = new MyCalculation ();
calculation .add(1, 2);
calculation .subtract(5, 1);
calculation .multiple(2, 4);

simple.....



Now i am going to explain another function which we can use to enhance our programming experience in javascript. Below given app i have studied from google and just want to clear how to program such apps.

As for beginner, it wouldn't be easy to understand so for faster to study i am writing points as numbers 1,2,3,4 you can go with these steps, so that it become easier to study.
In my case i will point function caller as point 1.





 
var myWebApp = (function() {
    "use strict"
 
 
 
 var myDiv= $("#myDiv"); // Getting Div Id  
 
    // private variables  
    var privateMessageVal;
    var privateAdditionalMessageVal;
   
   //Create an object which will hold our messages.

    var messageCtrls = {};
 
    var myconfigfile = {

        mySelector: null, // $("#myDiv")
        messageSelector: null, // $(".message")
        additionalMessageSelector: null, // $(".additional_message")
        options: {
            showOK: true,
            showCancel: true,
            warningLevel: 1,
        }
    }
 
writing ajax call functions for all events as a dynamic, in which we can pass parameter and result will be bind to messageCtrls object.


    // AJAX calls
    var getResult = function(msgs) {   ---------------------------------  (Point 8)
        $.ajax({
            url: '/urlOfAction',
            type: 'POST',
            dataType: "json",
            data: {'message' : msgs},
            success: function(data) {
                // ...
                messageCtrls.mainMessageDiv.html(data.result);
             
               //Here i am binding default controls for any dom to messageCtrls.

                messageCtrls = bindMessageControls();
                },
            error: function() {
                // ...
                }
        });
    };
 
    var inputClick = function(event) {   ---------------------------------  (Point 7)
        event.preventDefault();
        // depending on if you'll reuse these selectors throughout
        // the app I might have these as variables

        $('.loading').html('<img class="remove_loading" src="/graphics/loading.gif" alt="" />');
 
        // try to avoid these
        var msgs = $(".additionalMessage").val();
        // and use this
        var msgs = myconfigfile.additionalMessageSelector.val();
        // or
        var msgs = privateAdditionalMessageVal;
 
        if (msgs == ""){
            $("#msgs_empty").notification();   ////validating field if it is empty. and if not then call to ajax.
            $('.remove_loading').remove();
        } else {
            getResult(msgs);
        }
    };
 
//Here we will write all default controls needed for our App.

    var bindMsgControls = function () {
        var self = {};
 
        // Modal
        self.thisModal = $(".MessageModal");
 
        // CheckBoxs
        self.fooCb = $(".foo_checkbox");
       
        // Buttons
        self.okBtn = $(".btnOk");   ---------------------------------  (Point 6)
        self.cancelBtn = $(".btnCancel");
 
        // Divs
        self.mainMessageDiv = $(".main_message");   ---------------------------------  (Point 9)
        self.additionalMessageDiv = $(".addtional_message");
 
        //Help Icons
        self.HelpIcon = $(".help-icon");
 
        return self;
    };
 
    var bindVals = function () {
        //check to make sure we have a valid config passed in before we set the values
        if (!myconfigfile.messageSelector) throw "Invalid configuration object passed in init()";
       
        //bind the values to "private variables"
        pvtMessageVal = myconfigfile.messageSelector.val();
       
        //this control is optional, test existence
        if(config.additionalMessageSelector.length)
            pvtAdditionalMessageVal = myconfigfile.additionalMessageSelector.val();
    };
 
    var bindAllFunctions = function() {   ---------------------------------  (Point 4)
     
//This function will bind function to controls that are taken in bindMsgControls
//We can directly take our controls and bind function to them or we can call to object's controls, here messageCtrls's okBtn that is called by bindMsgControls, here we can get them and call function on its events.

        $("btnOk").on("click", inputClick)
     
//We can use as above but we have controls's object so we will write

        messageCtrls.okBtn.on('click, inputClick')   ---------------------------------  (Point 5)
    };
 
// On Init Call We need to bind controls and their functions first.

    var init = function () {   ---------------------------------  (Point 3)
        messageCtrls = bindMsgControls();
        bindAllFunctions();
    };
 
    var showMessage = function (cfg) {
        myconfigfile = cfg;
        bindVals();
        messageCtrls.thisModal.modal({
            show: true,
            keyboard: false,
            backdrop: "static"
        });
    };
   
    return {
        init: init,   ---------------------------------  (Point 2)
        show: showMessage,
        getMessage: getResult
        //anything else you want available
        //through myMessageApp.function()
        //or expose variables here too
    };
 
})();
 


//Usage

//A call to our above app init function

(Point 1)
--------------

$("document").ready(function () {
    myMessageApp.init();
});

So in totally we need to take care of 8 to 9 points which can clear our view. Here only our init of myapp will bind all controls and its functions, events, errors and pass it to its respective div.

That's way we can make our code look like self app. You can write in various ways but this technique will definitely perfect for modular pattern.




Tuesday 17 January 2017

Jquery Validation

12:06 Posted by Nikesh No comments

Hi, Today we practice on validation from beginner to advanced.

First we will grab js file required files jquery.js and jquery.validate.min.js

Jquery has validate function where we can write rule for our controls and gives properties to validate and in case if it not validate we can write error messages.

lets create a basic validation code in jquery.

      <form name="validationform" id="validationform" action="thankspage.html" method="post">

Name: <input type="text" name="name" class="form-control">  <br/>
Email: <input type="email" name="email" class="form-control"/>  <br/>

<input type="submit" value="Submit" name="submit" />

</form>


<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.16.0/jquery.validate.min.js"></script>


<script>
$(document).ready(function(){

console.log('My Validation Start..');

$("#validationform").validate({
            rules: {                      //-----------------------Writing Rule in rules{} object.
  name: {      //----------------------Writing Conditions for controls.
required: true,
minlength: 2,
                               maxlength: 50
             },
                          email: {
                                 required: true,
                                 email: true
                                     }
                    },
            messages: {             //----------Writing messages for each conditions written above.
                            name: {
required: "Name is required gmgu",
minlength: "Minimum 2 required",
maxlength: "maximum 50"
         },
                             email: {
                                        required: "Email required",
                                         email: "Invalid Email-id"
                                    }
                            }
               });


});
</script>



In last we should apply some css 


<style type="text/css">

input.valid
    {
        border: solid 1px #00FF00;
    }

    input.error
    {
         border: solid 1px #FF0000;
    }
   
    label.error
{
color: #FF0000;
display: none;
font-size: 18px;
min-width: 150px;
text-align: left;
z-index: 4;
}
</style>





Now lets jump more ahead. Every day we write many javascript codes and got too many plugins js which some times become messy or get complex so we will go one more step ahead where we will write simple code which don't have connection with plugins and we can use only with jquery itself.

So for this we will validate a form field also we will go with asp.net page because also i am from this background you can also go with above html and it will work with data-vald attributes

So let's get started..

First i will go with asp.net write a form where you have controls:



@Html.TextBoxFor(m => m.Name, new { @name = "ContatName",data_vald = "N", @id = "Name", @class = "form-control", @maxlength = "250", @placeholder = "Enter Name" })
@Html.ValidationMessageFor(m => m.Name)



@Html.TextBoxFor(m => m.SchoolOrganization, new { @name = "SchoolOrganization", data_vald = "S", @id = "SchoolOrganization", @class = "form-control", @maxlength = "250", @placeholder = "School/Organization" })
 @Html.ValidationMessageFor(m => m.SchoolOrganization)
                                             
@Html.TextBoxFor(m => m.PhoneNumber, new { @name = "PhoneNumber", data_vald = "P", @class = "form-control", @id = "PhoneNumber", @maxlength = "15", @placeholder = "Enter Phone Number" })
@Html.ValidationMessageFor(m => m.PhoneNumber)

@Html.TextBoxFor(m => m.EmailId, new { @name = "EmailId", data_vald = "E", @id = "EmailId", @class = "form-control", @maxlength = "50", @placeholder = "Enter E-mail Id" })
@Html.ValidationMessageFor(m => m.EmailId)



Note:-  I am using data_vald for data-vald attribute of  html and giving his respective names.



Then we will write jquery functions as below



<script type="text/javascipt">

 $(function () {

/////////////On every controls change event writing a function which will check if no any input found in control and if no any validation error exist on page then add error message and customize its borders.
             
                $('#Name').change(function () {
                    if (!$('#Name').val()) {
                        if ($("#Name").next(".field-validation-error").length == 0) // only add if not added
                        {
                            $('#Name').css('border', '1px solid #AC004A');
                            $("#Name").after("<div class='field-validation-error' style='color:#AC004A;margin-bottom: 20px;'>Name is required*</div>");
                            //$('#Name').focus();
                            //return;
                        }
                    } else {
                        $("#Name").next(".field-validation-error").remove(); // remove it
                        $('#Name').css('border', '1px solid black');
                    }
                });


                $('#PhoneNumber').change(function () {
                    if (!$('#PhoneNumber').val()) {
                      
                 if ($("#PhoneNumber").next(".field-validation-error").length == 0) // only add if not added
                        {
                            $('#PhoneNumber').css('border', '1px solid #AC004A');
                            $("#PhoneNumber").after("<div class='field-validation-error' style='color:#AC004A;margin-bottom: 20px;'>Please Enter Phone*</div>");
                          //  $('#PhoneNumber').focus();
                          //  return;
                        }
                    } else {
                        $("#PhoneNumber").next(".field-validation-error").remove(); // remove it
                        $('#PhoneNumber').css('border', '1px solid black');
                    }
                });
                $('#EmailId').change(function () {
                    debugger;

                    $("#EmailId").next(".field-validation-error").remove(); // remove it
                    $('#EmailId').css('border', '1px solid black');

                    if (!$('#EmailId').val()) {
                        if ($("#EmailId").next(".field-validation-error").length == 0) // only add if not added
                        {

                            $('#EmailId').css('border', '1px solid #AC004A');
                          //  $("#EmailId").after("<div class='validation' style='color:#AC004A;margin-bottom: 20px;'>Email address is required*</div>");
                         //   $('#EmailId').focus();
                          //  return;
                        }
                    } else {

                        if (validateEmail($('#EmailId').val())) {
                           // $("#EmailId").next(".field-validation-error").remove(); // remove it
                            $('#EmailId').css('border', '1px solid black');
                        }
                        else {
                            $('#EmailId').css('border', '1px solid #AC004A');
                            // $("#EmailId").after("<div class='validation' style='color:#AC004A;margin-bottom: 20px;'>Email address is required*</div>");
                        }

                     
                    }
                });

                $('#SchoolOrganization').change(function () {
                  

                    $("#SchoolOrganization").next(".validation").remove(); // remove it
                    $('#SchoolOrganization').css('border', '1px solid black');

                    if (!$('#SchoolOrganization').val()) {
                        if ($("#SchoolOrganization").next(".SchoolOrganization").length == 0) // only add if not added
                        {
                            $('#SchoolOrganization').css('border', '1px solid #AC004A');
                            //  $("#EmailId").after("<div class='validation' style='color:#AC004A;margin-bottom: 20px;'>Email address is required*</div>");
                            //   $('#EmailId').focus();
                            //  return;
                        }
                    } else {

                        if (validateEmail($('#SchoolOrganization').val())) {
                            $("#SchoolOrganization").next(".validation").remove(); // remove it
                            $('#SchoolOrganization').css('border', '1px solid black');
                        }
                        else {
                            $('#SchoolOrganization').css('border', '1px solid #AC004A');

                        }


                    }
                });




////After completing  each we will write validation function which can occur after form submit.


 function checkMandatoryFields(e) {
               
//// For this i am going to create an array which can store my data-vald attributes in array and from there i can loop and check which field was not valid values.

                          
                var validationcontent = [];

/////////////Emptying array before adding values.//////////////////
                for (var i = validationcontent.length; i > 0; i--) {

                    validationcontent.pop();

                }
Check for each controls validity and in case of not valid push that too validationcontent array.
So we can check their data-vald values and based on that update messages.


Checking each controls validity separately 


                if (!$('#BillingName').val()) {
                    validationcontent.push($('#BillingName').attr('data-vald'))
                }
                if (!$('#PhoneNumber').val()) {
                    validationcontent.push($('#PhoneNumber').attr('data-vald'))
                } if (!$('#EmailId').val()) {
                    validationcontent.push($('#EmailId').attr('data-vald'))
                } if (!$('#SchoolOrganization').val()) {
                    validationcontent.push($('#SchoolOrganization').attr('data-vald'))
                }

Loop through validationcontent and based on their values show messages for them

                for (var i = 0, len = validationcontent.length; i < len; i++) {
                    var s = validationcontent[i];
                    if (s == 'N') {
                   if ($("#Name").next(".field-validation-error").length == 0) // only add if not added
                        {
                            $('#Name').css('border', '1px solid #AC004A');
                            $("#Name").after("<div class='field-validation-error' style='color:#AC004A;margin-bottom: 20px;'>Name is required*</div>");
                           
                         
                        }
                        else {
                           $("#BillingName").next(".field-validation-error").remove(); // remove it
                            $('#BillingName').css('border', '1px solid black');

                        }
                    }
                    if (s == 'S') {
                        if ($("#SchoolOrganization").next(".validation").length == 0) // only add if not added
                                {
                                    $('#SchoolOrganization').css('border', '1px solid #AC004A');                                   
                                    $("#SchoolOrganization").after("<div class='validation' style='color:#AC004A;margin-bottom: 20px;'>School/Organization Name is required*</div>");
                                 
                                }
                            else {
                               $("#SchoolOrganization").next(".validation").remove(); // remove it
                                $('#SchoolOrganization').css('border', '1px solid black');
                            }
                    }
                    if (s == 'P') {
                        if ($("#PhoneNumber").next(".field-validation-error").length == 0) // only add if not added
                                {
                                    $('#PhoneNumber').css('border', '1px solid #AC004A');
                                    $("#PhoneNumber").after("<div class='field-validation-error' style='color:#AC004A;margin-bottom: 20px;'>Please Enter Phone*</div>");
                                  
                          
                        }
                        else {
                               $("#PhoneNumber").next(".field-validation-error").remove(); // remove it
                                $('#PhoneNumber').css('border', '1px solid black');
                           }
                    }
                    if (s == 'E') {
                        if ($("#EmailId").next(".field-validation-error").length == 0) // only add if not added
                        {
                            $("#EmailId").next(".field-validation-error").remove();
                                    $('#EmailId').css('border', '1px solid #AC004A');
                                    $("#EmailId").after("<div class='field-validation-error' style='color:#AC004A;margin-bottom: 20px;'>Email address is required*</div>");
                                   
                           
                        }
                        else {
                            $("#EmailId").next(".field-validation-error").remove(); // remove it
                               $('#EmailId').css('border', '1px solid black');
                           }
                    }
               
                }

After alerting return so that we can stop posting of form

                if (validationcontent.length != 0) {
                    return;
                }
       }
}




Tuesday 10 January 2017

Custom Search And Filters For Asp.net websites


Our Aim is to create a feature which can search multiple brand, multiple colors type products.
For this we first need to create form which contain multiple checboxes to filter, even you can also show checkbox of brand available from database. But in this post i am normally going to show you how normally logic can work for this.

So add below code in your view

 <form action="#" method="post" class="colorForm" id="colorForm">

                        <div class="form-group">

////////////Adding a hidden field which contain url to which we can use in ajax, in below url i am parsing pagination,searching parameters and in later ajax i will pass checkbox values///////////////

                             <input type="hidden" id="urltoquery" name="urltoquery" data-location="/home/AllProductWithRefiner?L=1&Name=@Name&pageno=@pageno&pagenoforpagination=@fixedpagination&rcount=@rcount">

////////////////////////////////Add all checkbox that contain brand or color code values///////////////
 /// //////////////////  here i am passing color code id ing checkbox value///////////////////////
                               
Color Refining Form

       <input type="hidden" id="urltoquery" name="urltoquery" data-location="/home/AllProductWithRefiner?L=1&Name=@Name&pageno=@pageno&pagenoforpagination=@fixedpagination&rcount=@rcount">
 <div class="checkbox">
     <label>
         <input type="checkbox" name="checkboxname" value="1" > <span class="colour white">                   </span> White (14)
       </label>
    </div>
 <div class="checkbox">
       <label>
         <input type="checkbox" name="checkboxname" value="2"  <span class="colour blue">                       </span> Blue (10)
      </label>
   </div>
 <div class="checkbox">
     <label>
         <input type="checkbox" name="checkboxname" value="3" > <span class="colour green">              </span> Green (20)
     </label>
   </div>
  <div class="checkbox">
     <label>
         <input type="checkbox" name="checkboxname" value="4" > <span class="colour yellow">             </span> Yellow (13)
     </label>
     </div>
  <div class="checkbox">
     <label>
         <input type="checkbox" name="checkboxname" value="5" > <span class="colour red">                   </span> Red (10)
     </label>
    </div>
 </div>

 </form>


Add below code in script on page

<script type="text/javascript>

    $(document).ready(function () {

               
//**********************Color Form ******************************************

////////////////Getting Url Where We Have To Post Our Data///////////////////////////

                    var url = $('#urltoquery').attr('data-location');

/////////////////////Getting Form All Chekbox///////////////////////////

                    var checkboxes = document.getElementsByName("checkboxname");

////Based on each checkbox storing check box value in value variable as a string seperated by "," if checkbox is checked/////////////////////////////

                    for (var i = 0; i < checkboxes.length; i++) {
                        var checkbox = checkboxes[i];
                        checkbox.onclick = (function (chk) {
                            return function () {
                                var value = "";
                                for (var j = 0; j < checkboxes.length; j++) {
                                    if (checkboxes[j].checked) {
                                        if (value === "") {
                                            value += checkboxes[j].value;
                                        } else {
                                            value += "," + checkboxes[j].value;
                                        }
                                    }
                                }

If you have noticed i am using URL of same page where i am coding. By this my code becomes smaller little. I am parsing data to same view  with l = 1 which makes layout null in top of view so it catch its dom. You can even write long html designing here too after returning.
                                var colorlocation = url + '&color=' + value;                                                                                              
       /////////////// Adding Parameters to URL  and parsing  URL to ajax actions/////////
  
                                $.ajax({
                                      type: "GET",
                                      url: colorlocation,
                                      data: '',
                                      success: function (data) {
                                          $("#loader").hide();

/////////////////////////You can desing your resultant product here//////////////////

                                          $('#mainDivId').html(data);  /////On its return i am passing data to dom
                                      },
                                      error: function (req, error) {
                                          if (error === 'error') { error = req.statusText; }
                                          var errormsg = 'There was a communication error: ' + error;
                                          console.log(errormsg);
                                          $("#loader").hide();
                                      },
                                      beforeSend: function (data) {
                                          $("#loader").show();
                                      }
                                  });
                             
                            }
                        })(checkbox);
                    }
               
                 

            </script>


In my case its call goes to a function declaration in same page because url i am passing is of same. You can return data via ajax through JsonResults() too.


 System.Data.DataTable dt = ShopAndStudio.Models.ecommerceQueriesModel.Allproductrefiner(rcount, pageno, ref recordcount, Name, color);                          ////color is collection of our checkbox values separated by ",".


////////////////////////And My function calls is here///////////////////////////

///////It calls a stored procedure of sql which in result return product////////////////

 static public DataTable Allproductrefiner(Nullable<Int32> counter, Nullable<Int32> PageNumber, ref Nullable<Int32> recordcount, string Name, string color)
        {
            SubSonic.Schema.StoredProcedure sp = new StoredProcedure("AllProductWithRefiner");
            sp.Command.AddParameter("@count", counter, DbType.Int64);
            sp.Command.AddParameter("@PageNo", PageNumber, DbType.Int64);

            sp.Command.AddParameter("@color", color, DbType.String);
            sp.Command.AddParameter("@Name", Name, DbType.String);

            DataSet ds = sp.ExecuteDataSet();
            DataTable dt = ds.Tables[0];

            recordcount = Convert.ToInt32(ds.Tables[1].Rows[0][0]);
            return sp.ExecuteDataSet().Tables[0];
        }


Now we will move to procedure but our data is useless until we separate each "," from value so for separating "," we need to create a function which can do it better as i did below:

Creating a function that can split "," from string and treat each as separate value.


CREATE FUNCTION dbo.SplitStringIntoInteger(@ColorList varchar(max))
RETURNS 
@ParsedList table         -- /////////Declaring A Table With int varable
(
   OrderID int
)
AS
BEGIN
    DECLARE @OrderID varchar(10), @Pos int               --////////Declaring above declared column and postion variable
    SET @ColorList = LTRIM(RTRIM(@ColorList))+ ','  --//// After Triming extra spaces adding ","
    SET @Pos = CHARINDEX(',', @ColorList, 1)       --///////Finding first postion of "," in color value we passed
    IF REPLACE(@ColorList, ',', '') <> ''       --/////  Replacing all "," with empty
    BEGIN
        WHILE @Pos > 0                       ---//////As we find "," in string so our pos value is 1
        BEGIN
                SET @OrderID = LTRIM(RTRIM(LEFT(@ColorList, @Pos - 1)))  

 ---///splitting "," from string and when splitted inserting to dynamic table

                IF @OrderID <> ''
                BEGIN
                        INSERT INTO @ParsedList (OrderID) 
                        VALUES (CAST(@OrderID AS int)) --Use Appropriate conversion
                END
                SET @ColorList = RIGHT(@ColorList, LEN(@ColorList) - @Pos)
               SET @Pos = CHARINDEX(',', @ColorList, 1)

        END
    END 
    RETURN  --- this will return table
END


Now our final procedure which will get data and return to json or our c# functions.


CREATE procedure AllProductWithRefiner          
@productID bigint = 0,          
@sku nvarchar(50) ='',          
@listOrder int = 0,          
@productName nvarchar(150)='',          
@defaultImage nvarchar(500) = '',          
@isProduct bit =1,          
@count bigint = 0,                                
@PageNo bigint =0,                            
@Name nvarchar(250) = '' ,
@color nvarchar(500) = ''      --////////color list parameter will comer here  
As          
  begin          
    Set NOCOUNT ON;          
if(@color='')       --/////Checking if our color value is null or not if null do other operation
begin
     ----------------------Do Other operations-----------------------
    end

  else if(@color<>'')  ---/////////else if color contain list values then start query operation
 begin
SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY productID DESC) AS rownum, utc.* From MyProductTable utc  where      
       utc.ProductId IN (Select ProductId from Product_Color_Map Where ColorId IN(Select * from SplitStringIntoInteger(@color)))) As MyProductTable  
       where (rownum >   CAST((5 * 0) AS VARCHAR(15))  AND rownum <=  + CAST((5 * (0 + 1)) AS VARCHAR(15)) )       
   SELECT count(utc.productID) as 'TotalCount' From MyProductTable utc  where (utc.isProduct = 1) 

----///////////This return my pagination data and based on color id values takes product on that color from product table
end
set NOCOUNT off          
End 



and i get my result as you can see below:



Simple Price Range Slider In Javascript



For this to be working we need a simple html range slider, so you can use simple  Min <input type="range" id="sliderange" min="1" max="200" /> Max

in which i have used min and max val for sliding value. You can go much better by using any free customized jquery range sliders.

Normally to make this we have to write an ajax which in result get products from backend and bind to html.

so copy Min <input type="range" id="sliderange" min="1" max="200" /> Max
and paste in your view or html then add below javascript in your page

<script type="text/javascript>

//////////////////Getting   range   slider////////////////////

        var slider = document.getElementById("sliderange");

//////////////////Adding a change event in javascript//////////////////////

        slider.addEventListener("change", function () {
            var rangevalue = $(this).val();
            $.ajax({
                        type: "GET",
                        url: "/home/getproductsbyprice",
                        data: { start: rangevalue},           //parsing slider value to ajax
                        success: function (data) {
                            if (data.success) {
                                var list = data.Result;       //Getting data
                                var isProduct = false;       
                                console.log(list);
                                var html = '';                 //Creating an html

/////////////////////////based on result value getting product detail by foreach in jquery and decorating based on need of product design you can even use css used for classes in designs//////////////////////////////////

                                $.each(list, function (key, value) {
                                       console.log(value.Image);                                   
                                       isProduct = true;
                                    
                                        html+= ' <div class="col-md-3 col-sm-4">'
                                        html+=  '<div class="product">'
                                        html+=  '<div class="flip-container">'
                                        html+= '<div class="flipper">'
                                        html+= ' <div class="front">'
                                        html+=  '<a href="detail.html">'
                                        html+= '  <img src="'+value.Image+'" alt="" class="img-responsive">'
                                        html+=     '  </a>'
                                        html+=    ' </div>'
                                        html+=    ' <div class="back">'
                                        html+=       '  <a href="detail.html">'
                                        html+= ' <img src="'+value.Image+'" alt="" class="img-responsive">'
                                        html+=           '</a>'
                                        html+=         ' </div>'
                                        html+=     ' </div>'
                                        html+=  '</div>'
                                        html+=  '<a href="detail.html" class="invisible">'
                                        html += ' <img src="'+value.Image+'" alt="" class="img-responsive">'
                                        html+=  '</a>'
                                        html+= ' <div class="text">'
                                        html += '  <h3><a href="detail.html">'+value.productName+'</a></h3>'
                                        html += ' <p class="price">$'+value.ourPrice+' </p>'
                                        html+=     ' <p class="buttons">'
                                        html+=              '   <a href="detail.html" class="btn btn-default">View detail</a>'
                                        html+=               '  <a href="basket.html" class="btn btn-primary"><i class="fa fa-shopping-cart"></i>Add to cart</a>'
                                        html+=            ' </p>'
                                        html+=        ' </div>'                           
                                        html+=      ' </div>'                           
                                        html += ' </div>';                                    
                                });

                                if (isProduct) {
                                    $('#myprod').html(html);
                                } else {
                                    $('#myprod').html('<div class="col-md-3 col-sm-4"><p><i>No any Product founds!</i></p></div>');
                                }
                                
                            }
                        },
                        error: function (req, error) {
                            if (error === 'error') { error = req.statusText; }
                            var errormsg = 'There was a communication error: ' + error;
                            console.log(errormsg);
                            $("#loader").hide();
                        },
                        beforeSend: function (data) {
                            //$("#loader").show();
                        }

                    });

</script>

And here i got my result.