Tag Archives: Calendar

[RESOLVED]Whether to validate the POST request parameters?

Hi. Sorry for my english.

There is such a method. It
checked
the parameters get request

[Route("Organization/{organizationId:int}/Category/{categoryId:int}/Calendar/Delete/{calendarId:int}")]
        public ActionResult Delete(int? calendarId, int? organizationId)
        {
            if (calendarId == null || organizationId == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Calendar calendar = db.Calendars.Find(calendarId);
            if (calendar == null || calendar.Category.OrganizationId != organizationId)
            {
                return HttpNotFound();
            }
            return View(calendar);
        }
[HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        [Route("Organization/{organizationId:int}/Category/{categoryId:int}/Calendar/Delete/{calendarId:int}")]
        public ActionResult DeleteConfirmed(int id)
        {
            Calendar calendar = db.Calendars.Find(id);
            db.Calendars.Remove(calendar);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

Whether it is necessary for safety purposes
check the parameters
POST
request
?

Hello,

It will be good practice to check all parameters on client and server side.

Regards

Thanks for the answer.

I meant, Do I need
to do this check in the query HttpGet and HttpPost?

if (calendar == null || calendar.Category.OrganizationId != organizationId)
            {
                return HttpNotFound();
            }

Hi DSerg,

DSerg

[Route("Organization/{organizationId:int}/Category/{categoryId:int}/Calendar/Delete/{calendarId:int}")]
        public ActionResult Delete(int? calendarId, int? organizationId)
        {
            if (calendarId == null || organizationId == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Calendar calendar = db.Calendars.Find(calendarId);
            if (calendar == null || calendar.Category.OrganizationId != organizationId)
            {
                return HttpNotFound();
            }
            return View(calendar);
        }

For this code, since you have specify the parameters’ type, so you don’t need to check parameters’ value. For example, if the type of organizationId is string (e.g. orgId), then that route won’t be matched.


DSerg

Hi. Sorry for my english.

There is such a method. It checked the parameters get request

[Route("Organization/{organizationId:int}/Category/{categoryId:int}/Calendar/Delete/{calendarId:int}")]
        public ActionResult Delete(int? calendarId, int? organizationId)
        {
            if (calendarId == null || organizationId == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            Calendar calendar = db.Calendars.Find(calendarId);
            if (calendar == null || calendar.Category.OrganizationId != organizationId)
            {
                return HttpNotFound();
            }
            return View(calendar);
        }
[HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        [Route("Organization/{organizationId:int}/Category/{categoryId:int}/Calendar/Delete/{calendarId:int}")]
        public ActionResult DeleteConfirmed(int id)
        {
            Calendar calendar = db.Calendars.Find(id);
            db.Calendars.Remove(calendar);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

Whether it is necessary for safety purposes
check the parameters
POST
request
?

For this code, you need check whether calendar is null or not.

Best Regards

Starain

[RESOLVED]How to create dynamic controls in MVC4

I need text box, drop down, calendar, Panel when drop down data is selected panel should open that contains controls text box, file upload index event should fire

If you want to add dynamic controls at run time, try partial view. Create a partial view with your needs(textbox, drop down, calender etc..) when you select a drop down value , using jquery ajax call that partial and bind it in the place you need to create
dynamic control.. 

[RESOLVED]does not contain a definition for 'Any'

I am creating a method for a piece of code that I intend to re-use.  The code works as part of a cshtml file, but when I move it into a method get this error message:

system.collections.generic.IEnumberable<dynamic> does not contain a definition for Any and no extension method Any

using System;
using System.Collections.Generic;
using System.Web;
using WebMatrix.Data;


/// <summary>
/// 
/// </summary>
public static class CalendarCleanUp
{
    public static CalendarCleanUp(int providerid)
    {
    var db = Database.Open("StarterSite");
    int thisweekno = DateUtils.GetWeekNo(DateTime.Now);
    bool haschanged = false;
    bool isactive = true;
    var records = db.Query("SELECT calRId, weekNo, WeekSelectionId FROM calRecords cr JOIN TimeSelections ts ON cr.calWId = ts.WeekSelectionId WHERE ProviderId=@0 AND isActive=@1", providerid, true);
    if (records.Any())
        {

In Visual Studio I can sometimes find what it need by hitting ALT SHFT F10, but that doesn’t work here.

Add 

using System.Linq;

to the top of the file.

thanks.

knockout js is working on main window but not working in popup window on asp.net / vb.net web application

Hello

I am developing a web application built with asp.net and vb.net

I have a page (update_status.aspx) which is using knockout js to display a datepicker depending upon the value selected by the user on select box. the code is like below.

 <%@ Page Title="" Language="VB" MasterPageFile="E4.master" AutoEventWireup="false" CodeFile="update-status.aspx.vb" Inherits="E4_Jobs_Details_Application_update_status" %>


<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server">

           <div class="entry-wrapper">
                <input type="hidden" id="appId" value="<%= VacancyApplication.ID%>" />

                <div class="form-element">
                    <label>Current status</label>
                    <input type="text" readonly="readonly" value="<%= VacancyApplication.Status%>" />
                </div>

                <div class="form-element">
                    <label>New status (required)</label>
                    <select id="comNewStatus" runat="server" datavaluefield="id" datatextfield="name" class="nFee"></select>
                </div>


                <div data-bind="visible: statusId() == 12">
                    <label>
                        Start date (required, format: DD-MMM-YYYY)
                    </label>
                    <div class="input-append">
                        <span class="add-on "><span class="icon-calendar"></span></span>
                        <input class="dp" size="16" type="text" value="" runat="server" id="txtStartDate" />
                    </div>
                </div>
            </div>


</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ScriptContent" runat="Server">
    <script  src="~/_resx/js/jquery-1.8.3.min.js"></script>
    <script src="~/_resx/js/json2.min.js"></script>
    <script src="~/_resx/js/knockout-2.2.1.js"></script>
    <script src="~/_resx/js/knockout.mapping-latest.js"></script>

    <script type="text/javascript">

        var ViewModel = function () {
            var self = this;
            self.histories = ko.observableArray([]);
            self.statusId = ko.observable(0);
            self.feeType = ko.observable(0);
            self.agencyApp = ko.observable(false);
            self.offeredSalary = ko.observable(0);
            self.finalSalary = ko.observable(0);
            self.introductionFee = ko.observable(0);
            
        };
        var vm = new ViewModel();
        ko.applyBindings(vm);

        $(function () {
            $("select.chosen").chosen();
            dimNav('vacancy');

            var aid = $('#appId').val(), feeType = $('#feeType').val(), agencyApp = $('#agencyApp').val();
            vm.feeType(parseInt(feeType));
            vm.agencyApp(agencyApp);

            $('.nFee').change(function () {
                vm.statusId(parseInt($(this).val()));
            });
            

            //numeric only
            $('.txtOfferedSalary, .txtFinalIntroductionFee,.txtFinalSalary').keydown( function(event) {
                // Allow: backspace, delete, tab, escape, and enter
                if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 ||
                    (event.keyCode == 65 && event.ctrlKey === true) ||
                    // Allow: home, end, left, right
                    (event.keyCode >= 35 && event.keyCode <= 39)) {
                    return;
                } else {

                    if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) {
                        event.preventDefault();
                    }
                }
            });



            $.when(
                $.ajax({
                    type: "POST",
                    url: "/_services/UtilityService.asmx/applicationstatushistories",
                    data: "{id:" + aid + "}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    cache: true
                })).done(function (r) {
                    vm.histories($.parseJSON(r.d));
                    //console.log();
                    momentize();
                });
        });
    </script>
</asp:Content>

The problem is this knockoutjs doesnot work when i convert this page as popup page by changing its master page (like below). that is the calender doesnot come up when user selects the right status.

<%@ Page Title="" Language="VB" MasterPageFile="E4_Popup.master" AutoEventWireup="false" CodeFile="update-status.aspx.vb" Inherits="E4_Jobs_Details_Application_update_status" %>

Both E4.master and E4_Popup.master is using the same style and same code file .

<%@ Master Language="VB" CodeFile="E4.master.vb" Inherits="_resx_E4" %>

the only difference is they are different files and E4_Popup.master doesnot contains the extra bits of the web page (e.g; headers and footers ).

even if copy E4.master page as E4_Popup.master page and refer it to the update status page .. the calender does not come up. It just not working on the pages other than E4.master page.

I dont understand what the problem is..

What shall I do? Please help me with right advice. 

If you need more information please let me know.

Hi,

make sure the new master page file refers to the knockout.js file from its header too.

I had make sure of that… even if i just copy the E4.master page and save it as E4_Popup.master page and refere it to update_status.aspx page that doesnot work.

raju dasa

Hi,

make sure the new master page file refers to the knockout.js file from its header too.

Hi bashabi,

In your code,i didn’t see any javascipt reference code about knockout.js

please make sure that you have code like below in your page:

  <script src="../Scripts/knockout.js"></script>

Best Regards,

Kevin Shen.

the references are in master page.  i also have added the reference in main page…. but it did not work.

I have included the codes for both the master pages.

below is the code for my master page for popup . please have a look. and advice me

<%@ Master Language="VB" CodeFile="E4_Popup.master.vb" Inherits="_resx_E4_Popup" %>


<!doctype html>

<html lang="en">
<head id="Head1" runat="server">

    <meta name="robots" content="noindex, nofollow">
    <meta name="googlebot" content="noindex, nofollow">
    <link href='https://fonts.googleapis.com/css?family=Roboto:400,300,100' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" media="screen" href="/_resx/css/e4-popup-min.css" />
    <link rel="stylesheet" type="text/css" media="screen" href="/_resx/css/bootstrap.css" />
    <link rel="stylesheet" type="text/css" media="print" href="/_resx/css/e4_print_1.css" />
    <script  src="/_resx/js/jquery-1.8.3.min.js"></script>
    <script src="/_resx/js/json2.min.js"></script>
    <script src="/_resx/js/knockout-2.2.1.js"></script>
    <script src="/_resx/js/knockout.mapping-latest.js"></script>

    <script type="text/javascript">if ($.browser.msie && parseInt($.browser.version) < 8) { window.location = '/badbrowser.aspx'; }</script>
    <script>
        $(function () {
            if ($.browser.msie && parseInt($.browser.version, 10) === 6) {
                $('.row div[class^="span"]:last-child').addClass("last-child"); $('[class*="span"]').addClass("margin-left-20"); $(':button[class="btn"], :reset[class="btn"], :submit[class="btn"], input[type="button"]').addClass("button-reset"); $(":checkbox").addClass("input-checkbox"); $('[class^="icon-"], [class*=" icon-"]').addClass("icon-sprite");
                $(".pagination li:first-child a").addClass("pagination-first-child");
            }
        })
    </script>

     
</head>
<body>
    <form id="form1" runat="server">
      <asp:ScriptManager runat="server" ID="ScriptManager" />
        <div class="loading"></div>
        <div class="popup-wrapper">

            <asp:ContentPlaceHolder runat="server" ID="MainContent" />
        </div>
    </form>
    <script src="https://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <script src="/_resx/js/respond.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBUCn2Ql9C5kHJbIxYgghwA3Q5zmoTahIk&sensor=true"></script>
    <script src="/_resx/js/json2.min.js"></script>
    <script src="/_resx/js/knockout-2.2.1.js"></script>
    <script src="/_resx/js/knockout.mapping-latest.js"></script>
    <script src="/_resx/js/bootstrap.min.js"></script>
    <script src="/_resx/js/bootbox.min.js"></script>
    <script src="/_resx/js/typeahead.min.js"></script>
    <script src="/_resx/js/trunk8.js"></script>
    <script src="/_resx/js/moment.js"></script>
    <script src="/_resx/js/chosen.jquery.min.js"></script>
    <script src="/_resx/js/jquery.cookie.js"></script>
    <script src="/_resx/js/date.format.js"></script>
    <script src="/_resx/js/jquery-datepicker.min.js"></script>
    <script src="/_resx/js/highcharts.js"></script>
    <script src="/_resx/js/spinners.min.js"></script>
    <script src="/_resx/js/tipped.js"></script>
    <script src="/_resx/js/datepicker.js"></script>
    <script src="/_resx/js/jquery.autosize-min.js"></script>
    <script src="/_resx/js/jquery.tinysort.min.js"></script>
    <script src="/_resx/js/jquery.mousewheel.js"></script>
    <script src="/_resx/js/jquery.jscrollpane.js"></script>
    <script src="/_resx/js/jquery.gmap.js"></script>
    <script src="/_resx/js/jquery.signalR-1.0.1.min.js"></script>
    <script src="/signalr/hubs"></script>
    <script src="/_resx/js/e5-min.js"></script>


    <asp:ContentPlaceHolder runat="server" ID="ScriptContent" />
    <script type="text/javascript">
                function setSize() {
                        window.resizeTo(300, 300);
                }

                function SetWindow() {
                            var height = 400                      //Set height
                            var width = 400                        //Set width
                            var name = "winname"             //Set window name
                            var top = 20                             //Set distance from top
                            var left = 20                             //Set distance from bottom
                            url = window.location.href;
                            window.document.statusbar.enable = false;

                            if (document.location.search == '') {
                                newwin = window.open(url, name, "fullscreen=no,toolbar=no,status=no,menubar=no,scrollbars=no,resizable=no,directories=no,location=no,width=" + width + ",height=" + height + ",left=" + left + ",top=" + top);

                            }
                }


                var reseizeParentColorBox = function () {
                    parent.$.colorbox.resize({
                        innerHeight: $('body').height() + 100
                    });

                    $('input[type="text"]:first').focus();
                };

                //momentise times

                var momentize = function () {
                    $('.moment').each(function () {
                        var m = moment($(this).attr('data-time'));
                        var $time = m.valueOf();
                        if (m.diff(moment(), 'days') < 0) {
                            $(this).removeAttr('rel').html(moment($time).format('MMMM Do, YYYY'));
                        } else {
                            $(this).html(moment($time).fromNow()).attr({
                                'title': moment($time).format('MMMM Do, YYYY h:mm a')
                            });
                        }
                    });
                };

                function loaderStart() {
                    $('.loading').show();
                }

                function loaderStop() {
                    $('.loading').fadeOut();
                }



        var _gaq = _gaq || [];
        _gaq.push(['_setAccount', 'UA-31876528-1']);
        _gaq.push(['_trackPageview']);



        (function () {
            var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
            ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
        })();

    </script>
</body>
</html>

below is my code for master page for main screen

<%@ Master Language="VB" CodeFile="E4.master.vb" Inherits="_resx_E4" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en">
<head runat="server">
    <title></title>
    <meta name="robots" content="noindex, nofollow">
    <meta name="googlebot" content="noindex, nofollow">
     <link href='https://fonts.googleapis.com/css?family=Roboto:400,300,100' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="/_resx/css/e5-min.css" />

    <link rel="stylesheet" type="text/css" media="print" href="/_resx/css/e4_print_1.css" />
    <script src="/_resx/js/jquery-1.8.3.min.js"></script>
  
    <script type="text/javascript">if ($.browser.msie && parseInt($.browser.version) < 8) { window.location = '/badbrowser.aspx'; }</script>
    <script>
        $(function () {
            if ($.browser.msie && parseInt($.browser.version, 10) === 6) {
                $('.row div[class^="span"]:last-child').addClass("last-child"); $('[class*="span"]').addClass("margin-left-20"); $(':button[class="btn"], :reset[class="btn"], :submit[class="btn"], input[type="button"]').addClass("button-reset"); $(":checkbox").addClass("input-checkbox"); $('[class^="icon-"], [class*=" icon-"]').addClass("icon-sprite");
                $(".pagination li:first-child a").addClass("pagination-first-child");
            }
        })
    </script>

</head>
<body>
    <form id="form1" runat="server" style="height: 100%;">
        <asp:ScriptManager runat="server" ID="ScriptManager" />
        <div class="loading"></div>
        <div class="navbar navbar-fixed-top">
            <div class="navbar-inner">
                <div class="navbar-search pull-left q-search">
                    <input type="text" id="qSearch" placeholder="type job title or candidate name..." />
                    <input type="hidden" value="" id="qSearchU" />
                </div>
                <ul class="nav pull-right account">
                    <li class="user  dropdown">
                            <div class="user">
                                <%= LocalHelper.CurrentUserName()%> <b class="caret"></b>
                            </div>

                    </li>
                </ul>

                               <a class="pull-right logout" href="/logout.aspx">Log out</a>
            </div>
        </div>

        <div class="help">
            <div class="help-inner">
                <iframe id="helpframe" src="/E4/help/index.html" scrolling="no" frameborder="0" height="auto" width="100%">Sorry, iframes are not supported.</iframe>
            </div>
        </div>

         <div class="g-wrapper">
                            <a href="#menu" id="menuLink" class="pure-menu-link">
                                        <img src="/_resx/images/navicon-png2x.png" width="20" alt="Menu toggle">
                            </a>
                            <div class="fix-nav-bg scroller">
                                        <div class="fix-nav">
                                                    <a class="nav-link " href="/E4/Default.aspx">
                                                        <i class="dashboard"></i>
                                                        <span>Dashboard</span>
                                                    </a>
                                                    <a class="nav-link " href="/E4/Jobs/Open.aspx">
                                                        <i class="vacancy"></i>
                                                        <span>Jobs</span>
                                                    </a>
                                        </div>
                            </div>
                            <asp:ContentPlaceHolder runat="server" ID="MainContent" />
        </div>
        <a href="http://mypeoplebiz.com" class="copy">&copy; mypeoplebiz</a>
    </form>

    <script src="/_resx/js/respond.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js"></script>
    <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBUCn2Ql9C5kHJbIxYgghwA3Q5zmoTahIk&sensor=true"></script>


    <script src="/_resx/js/json2.min.js"></script>
    <script src="/_resx/js/knockout-2.2.1.js"></script>
    <script src="/_resx/js/knockout.mapping-latest.js"></script>
    <script src="/_resx/js/bootstrap.min.js"></script>
    <script src="/_resx/js/bootbox.min.js"></script>
    <script src="/_resx/js/typeahead.min.js"></script>
    <script src="/_resx/js/trunk8.js"></script>
    <script src="/_resx/js/moment.js"></script>
    <script src="/_resx/js/chosen.jquery.min.js"></script>
    <script src="/_resx/js/jquery.cookie.js"></script>
    <script src="/_resx/js/date.format.js"></script>
    <script src="/_resx/js/jquery-datepicker.min.js"></script>
    <script src="/_resx/js/highcharts.js"></script>
    <script src="/_resx/js/spinners.min.js"></script>
    <script src="/_resx/js/tipped.js"></script>
    <script src="/_resx/js/datepicker.js"></script>
    <script src="/_resx/js/jquery.autosize-min.js"></script>
    <script src="/_resx/js/jquery.tinysort.min.js"></script>
    <script src="/_resx/js/jquery.mousewheel.js"></script>
    <script src="/_resx/js/jquery.jscrollpane.js"></script>
    <script src="/_resx/js/jquery.gmap.js"></script>
    <script src="/_resx/js/jquery.signalR-1.0.1.min.js"></script>
    <script src="/signalr/hubs"></script>
    <script src="/_resx/js/e5-min.js"></script>
    <asp:ContentPlaceHolder runat="server" ID="ScriptContent" />
    <script type="text/javascript">

        function openSupport() {

            var URL = '/E4/help/index.html';
            window.open(URL, '', 'toolbar=0,scrollbars=0,location=no,statusbar=0,menubar=0,resizable=1,width=900,height=700,left = 560,top = 130');

        }



        var _gaq = _gaq || [];
        _gaq.push(['_setAccount', 'UA-31876528-1']);
        _gaq.push(['_trackPageview']);

        (function () {
            var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
            ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
            var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
        })();

    </script>
</body>
</html>

Hi bashabi,

I suggest that you can use F12 to debug your page ,see if it has any error message.

If does,please post here.

Best Regards,

Kevin Shen.

There are 2 error message which I have found in the popup page but not in main page while debugging. I have provided them including the code (where it indicated the error) below. 

these codes are written in both of the two master page. 

I have tried disabling these lines of code and run… but its the same result.

please have a look and advice

SCRIPT5007: Unable to get property ‘msie’ of undefined or null reference
update-status_popup.aspx, line 17 character 13

    <script>
        $(function () {
            if ($.browser.msie && parseInt($.browser.version, 10) === 6) {
                $('.row div[class^="span"]:last-child').addClass("last-child"); $('[class*="span"]').addClass("margin-left-20"); $(':button[class="btn"], :reset[class="btn"], :submit[class="btn"], input[type="button"]').addClass("button-reset"); $(":checkbox").addClass("input-checkbox"); $('[class^="icon-"], [class*=" icon-"]').addClass("icon-sprite");
                $(".pagination li:first-child a").addClass("pagination-first-child");
            }
        })
    </script>

SCRIPT5007: Unable to get property ‘resize’ of undefined or null reference
update-status_popup.aspx, line 304 character 21

                var reseizeParentColorBox = function () {
                    parent.$.colorbox.resize({
                        innerHeight: $('body').height() + 100
                    });

                    $('input[type="text"]:first').focus();
                };

When I run the application … for the E4.master page,E4_popup.master page and update_status_popup.aspx page the following type of warning comes up

Namespace or type specified in the Imports ‘Telerik.WebControls’ doesn’t contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn’t
use any aliases.

[RESOLVED]Return last date in month

I have an asp.net web page that I need a javascript function to return the last day of a month based on a date passed from a TextBox.  For example, if I pass 10/10/2014 I want it to return 10/31/2014.  How can I do that in javascript?  Thanks.

You could use a function like this :

function GetLastDayOfMonth(date){
   // Attempt to parse the Date passed in
   var currentDate = new Date(date);
  
   // Get the last day of that month
   var targetDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);
   
   return targetDate;
}

You can see a working example here, which would return a Date object of "October 31st 2014" provided the input your example shows (10/10/2014). If you needed to actually output your Date in that format,
you would just need to adjust it slightly to handle the formatting :

function GetLastDayOfMonth(date){
  
   // Attempt to parse the Date passed in
   var currentDate = new Date(date);
  
   // Get the last day of that month
   var targetDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);
   
   // Outputs your date as a string in the format : "MM/dd/yyyy"
   return ('0' + (targetDate.getMonth()+1)).slice(-2) + '/' + ('0' + (targetDate.getDate())).slice(-2) + '/' + targetDate.getFullYear();
}

An example with formatting can be seen
here
.

Perfect! Thanks.

One other question.  When I use this js function on a TextBox with a CalendarExtender control and click on it after setting the value from the function, it does not show the new month but rather the old month before the change.

[RESOLVED]Clientside event for Dropdownlist

Hi Friends,

I have 2 drop down lists ddl1 and ddl2. After selecting an item from the list for ddl1,i select an item from the list ddl2. If the item selected for ddl2 is not the same as the item selected for ddl1,an OK/CANCEL alert box should appear showing "Location
Name and Charged To Location are not the same. Do you want to proceed?".If clicked OK then nothing happens and return to the same page. If clicked CANCEL, ddl2 is cleared and return to the same page with focus on ddl2. Is there any clientside event to do this?
I tried writing it in the SelectionChangedEvent of ddl2 in the server side, but the alert box does’nt appear in the same page and it appears in another blank page.Below is the code.

Protected Sub ddl2_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ddl2.SelectedIndexChanged
If ddl2.Text <> ddl1.SelectedItem.Text Then
Dim CSM As ClientScriptManager = Page.ClientScript
If Not ReturnValue() Then
Dim strconfirm As String = "<script>if(!window.confirm(‘Location Name and Charged To Location are not the same. Do you want to proceed?’)){window.location.href=’Presences.aspx’}</script>"
CSM.RegisterClientScriptBlock(Me.[GetType](), "Confirm", strconfirm, False)
ddlLocName.Focus()
End If
End If

Private Function ReturnValue() As Boolean
Return False
End Function

Can someone help me with a client side event for dropdownlist.

Thanks.

You can achive it using simple js like below:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <title>Uploader Demo</title>
    <script language="javascript" type="text/javascript">
        function OnChange(dropdown) {
            var myindex = dropdown.selectedIndex;
            var SelValue = dropdown.options[myindex].value;
            var objFirstDDL = document.getElementById('<%= DropDownList1.ClientID %>');
            var oldidx = objFirstDDL.selectedIndex;
            var FirstValue = objFirstDDL.options[oldidx].value;
            if (SelValue != FirstValue) {
                var blnResult = confirm("Location Name and Charged To Location are not the same. Do you want to proceed?");
                if (blnResult) {
                    return false;
                }
                else {
                    dropdown.selectedIndex = 4;
                    return false;
                }
            }
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:DropDownList runat="server" ID="DropDownList1" AutoPostBack="false">
            <asp:ListItem Text="Text1" Value="Value1"></asp:ListItem>
            <asp:ListItem Text="Text2" Value="Value2"></asp:ListItem>
            <asp:ListItem Text="Text3" Value="Value3"></asp:ListItem>
        </asp:DropDownList>
        <asp:DropDownList runat="server" ID="DropDownList2" AutoPostBack="false" onchange='return OnChange(this);'>
            <asp:ListItem Text="Text1" Value="Value1"></asp:ListItem>
            <asp:ListItem Text="Text2" Value="Value2"></asp:ListItem>
            <asp:ListItem Text="Text3" Value="Value3"></asp:ListItem>
            <asp:ListItem Text="" Value=""></asp:ListItem>
        </asp:DropDownList>
        <asp:DropDownList runat="server" ID="DropDownList3">
        </asp:DropDownList>
        <asp:DropDownList runat="server" ID="DropDownList4">
        </asp:DropDownList>
    </div>
    </form>
</body>
</html>

Thanks Friend..It worked perfectly.

I need 1 more similar help from you. I have 2 textboxes to enter the dates and a checkbox next to it. Dates are entered through calender control in JS.If the entered dates are greater than the present date,the checkbox should be disabled else the checkbox
should be enabled. Should I use javascript for this purpose? Through which event can I do this. Below are my code for textboxes.

<asp:TextBox ID="txtFromDate" runat="server" CssClass="txtbox" Width="80px"
onfocus="showCalendarControl(this)" AutoPostBack="True"></asp:TextBox>

<asp:TextBox ID="txtToDate" runat="server" CssClass="txtbox" Width="80px"
onfocus="showCalendarControl(this)" AutoPostBack="True"></asp:TextBox>

I Tried to write a server side code like this, but didnt work.

If CDate(txtFromDate.Text) > Date.Now.Date Or CDate(txtToDate.Text) > Date.Now.Date Then
chkCon.Enabled = False
Else
chkCon.Enabled = True
End If

Hope you can help me.

Thanks.

[RESOLVED]Javascript to disable the check box

I have 2 Textboxes to enter the dates and a Checkbox next to it. Dates are entered through calender control in JS. If the entered dates are greater than the present date,the checkbox should be disabled else the checkbox should be enabled. Should I use javascript
for this purpose? Through which event can I do this. Below are my code for textboxes.

<asp:TextBox ID="txtFromDate" runat="server" CssClass="txtbox" Width="80px" 
onfocus="showCalendarControl(this)" AutoPostBack="True"></asp:TextBox>

<asp:TextBox ID="txtToDate" runat="server" CssClass="txtbox" Width="80px" 
onfocus="showCalendarControl(this)" AutoPostBack="True"></asp:TextBox>

I Tried to write a server side code like this, but didnt work.

If CDate(txtFromDate.Text) > Date.Now.Date Or CDate(txtToDate.Text) > Date.Now.Date Then
chkCon.Enabled = False
Else
chkCon.Enabled = True
End If

i need the event to happen just after the dates are entered in the 2 Textboxes. Someone please help me.

Thanks.

Hi sinjumujeeb,

Please try the following code:

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Input Dates </title>
    <script type="text/javascript">

        function disableCheckBox()
        {
            
            var dateToday = new Date();
            var txtFromDate =new Date( document.getElementById('TextBox1').value);
            if (dateToday.getTime() <txtFromDate.getTime()) {
                document.getElementById('CheckBox1').disabled = true;
            }
            else {
                alert('please enter a former date');
            }

        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
     <asp:toolkitscriptmanager ID="Toolkitscriptmanager1" runat="server"></asp:toolkitscriptmanager>
    <div>
        From date:<asp:TextBox ID="TextBox1" ReadOnly="true" runat="server" onchange="disableCheckBox()"></asp:TextBox><asp:Label ID="lbl_Click" runat="server" Text="CLICK ME"></asp:Label> <asp:CalendarExtender ID="CalendarExtender1" TargetControlID="TextBox1" PopupButtonID="lbl_Click" PopupPosition="TopRight" runat="server"></asp:CalendarExtender>
        To date:<asp:TextBox ID="TextBox2" runat="server" onchange="disableCheckBox()"></asp:TextBox> <asp:CalendarExtender ID="CalendarExtender2" TargetControlID="TextBox2" runat="server"></asp:CalendarExtender>
        <asp:Label ID="Label1" runat="server" Text="Calculate" onclick="showDateDifference()"></asp:Label>
        <%--<input type="checkbox" id="CheckBox1" />--%>
        <asp:CheckBox ID="CheckBox1" runat="server" />
    </div>
    </form>
</body>
</html>

and revert for more details.

I think there are following options

1) you change showCalendarControl() so that it not only sets a value but also disable required controls.
2) you do not change showCalendarControl() but create a javascript which will check in a loop (e.g. every second, using setTimeout() function) for a value of the control and disable required controls.
3) you use another calendar which will let you do what you want – example: http://stackoverflow.com/questions/6471959/jquery-datepicker-onchange-event-help 

P.S.

You cannot use AutoPostBack="True" because there is no postback event fired. So the code which you have in the code-behind will not fire on the change in calendar but only if you click on submit button or any other server control on the form.

Hi sinjumujeeb

From my point of view, I suggest you use the TextBox onchange event. Please try to use the following code:

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

    <script type="text/javascript">
        function ValidateDate() {
            var dateToday = new Date();
            var txtFromDate = new Date(document.getElementById('TextBox1').value);
            if (dateToday.getTime() < txtFromDate.getTime()) {
                document.getElementById('CheckBox1').disabled = true;
                alert('please enter a former date');
            }
            else {
                document.getElementById('CheckBox1').disabled = false;
            }

        }
    </script>

        <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server"></asp:ToolkitScriptManager>
        <div>
            Date:
            <asp:TextBox ID="TextBox1" runat="server" onchange="ValidateDate();" ></asp:TextBox>
<asp:CalendarExtender ID="CalendarExtender1" TargetControlID="TextBox1" PopupButtonID="TextBox1" runat="server"></asp:CalendarExtender> <br /> <asp:CheckBox ID="CheckBox1" runat="server" /> </div>

If you have any other questions about my reply, please let me know freely.

Best Regards,
Dillion

any suggestion is welcome…JSON Response – one substring not being recognized by my code

This is code that has been gleaned from "inline editing of the web grid" at
www.mikesdotnetting.com

All code below works, the drop downs are properly populated, the grid displays as it should, the EDIT and SAVE work, the JSON write to CreateCalendarF works, the code inside there correctly changes the db, and the code there responds with the JSON string
exactly as I want it to.

The problem is that the calWId/WeekSelectionCal column in grid row that was updated does not reflect the change that was send over with the JSON response.  After I refresh the page it shows it correctly. All the other changes are being recognized

My problem is related to self inflicted confusion caused by different names for the same thing in two tables in the db.

calRecords  calr which is the main table  uses calWId

TimeSelections ts is the table that is being joined on JOIN TimeSelections ts ON calr.calWId = ts.WeekSelectionId

The last piece of code below is the JSON response retrieved from the Response in the browser.

<script>
    $(function () {

        $('.edit-mode').hide();
        $('.edit-calendar').on('click', function () {
            var tr = $(this).parents('tr:first');
            tr.find('.edit-mode, .display-mode').toggle();
        });
        $('.save-calendar').on('click', function () {
            var tr = $(this).parents('tr:first');
            var ownerlocationid = $(this).prop('id');
            var location = tr.find('Location').val();
            var calwid = tr.find('#calWId').val();
            var caldid = tr.find('#calDId').val();
            var caloid = tr.find('#calOId').val();
            var qty = tr.find('#Qty').val();
            var c12 = tr.find('#C12').val();
            var c11 = tr.find('#C11').val();
            var c10 = tr.find('#C10').val();
            var c9 = tr.find('#C9').val();
            var c8 = tr.find('#C8').val();
            var c7 = tr.find('#C7').val();
            var c6 = tr.find('#C6').val();
            var c5 = tr.find('#C5').val();
            var c5min = tr.find('#C5min').val();
            var isactive = tr.find('#isActive').is(':checked');
            $.post(
                    '/Methods/CreateCalendarF',
                    { OwnerLocationId: ownerlocationid, Location: location, calWId: calwid, calDId: caldid, calOId: caloid, C12: c12, C11: c11, C10: c10, C9: c9, C8: c8, C7: c7, C6: c6, C5: c5, C5min: c5min, isActive: isactive },
                    function (cal) {
                        tr.find('#location').text(cal.Location);
                        tr.find('#weekselectioncal').text(cal.WeekSelectionCal);
                        tr.find('#calday').text(cal.calDay);
                        tr.find('#calorder').text(cal.calOrder);
                        tr.find('#qty').text(cal.Qty);
                        tr.find('#c12').text(cal.C12);
                        tr.find('#c11').text(cal.C11);
                        tr.find('#c10').text(cal.C10);
                        tr.find('#c9').text(cal.C9);
                        tr.find('#c8').text(cal.C8);
                        tr.find('#c7').text(cal.C7);
                        tr.find('#c6').text(cal.C6);
                        tr.find('#c5').text(cal.C5);
                        tr.find('#c5min').text(cal.C5min);
                        tr.find('#isactive-display').removeAttr("disabled").attr('checked', cal.isActive).attr('disabled', true);
                    }, "json");
            tr.find('.edit-mode, .display-mode').toggle();
            $('.edit-mode').val('0');
        });
    })
</script>

grid.Column("Week", style: "col3", format:
                    @<text>
                    <span id="calweek" class="display-mode">@item.WeekSelectionCal</span>
                    @Html.DropDownList("calWId", null, weekselections, item.calWId, new { @class = "edit-mode" })
                    </text>),

var weekselections = db.Query("SELECT TOP (4) WeekSelectionId, WeekSelectionCal FROM TimeSelections")
        .Select(weekselection => new SelectListItem
            {
            Value = weekselection.WeekSelectionId.ToString(),
            Text = weekselection.WeekSelectionCal
            });

{"ownerLocationId":61,"Location":"JStables","WeekSelectionCal":"tbd","calDay":"tbd","calOrder":"tbd","Qty":3,"isActive":false,"C12":2,"C11":0,"C10":0,"C9":0,"C8":0,"C7":0,"C6":0,"C5":0,"C5min":1} 

[RESOLVED]How How to Filter into IList Object in MVC C#

Hello,

I have an query how to filter IList object by passing an ID as integer, Below is code 

 IList<F> ListResult  = objBll as IList<F>;

The above object contains 3 rows how to filter by passing ID = 1 to get the row.

Thanks,

Shabbir

You can use the where lambda expression or linq query

http://msdn.microsoft.com/en-us/library/bb534803(v=vs.110).aspx

Your code should be something similar

var result = ListResult.where(f => f.id == 1)

Basically i have below class which doesn’t exist in Database how to Cast as DbSet, So that i can use to my Basecontroller class.

public class Category_View
        {
            public int ID { get; set; }
            public int CalendarID { get; set; }
            public int CategoryID { get; set; }
            public string Title { get; set; }
            public string CategoryName { get; set; }
        }

Thanks in Advance

Shabbir

you cannot cast your class to dbset. either u use entity framework (this will map your class to your generated table/columns or it will generate your table automatically for u) or u have to write your business logic and data access logic yourself.

shabbir_215

shabbir_215

just implement conversion logic

public class
Category_View
       
{
           
public int ID
{ get;
set;
}
           
public int
CalendarID {
get;
set; }
           
public int
CategoryID {
get;
set; }
           
public string
Title {
get;
set; }
           
public string
CategoryName {
get;
set; }
       
}

Forexample:

private static Category_View ConvertToEntity(youDbSetType entity)

{

return new Category_View

{

Field1 = entity.Field1,

Field2= entity.Field2

};

}

Thanks Thai

I have add the below code but how to convert to DBset using below function

private static Category_View ConvertToEntity(Category_View entity)
        {

            return new Category_View
            {

                CalendarID = entity.CalendarID,
                CategoryID = entity.CategoryID,
                CategoryName = entity.CategoryName,
                ID= entity.ID,
                Title = entity.Title
            };

        }

I tried this way but didn’t workFrown

 protected DbSet<Category_View> dbEntitySetp = ConvertToEntity(Category_View) as DbSet<Category_View>;

projection operators

// fake dbSet returned

var c = new List<Category_View>()
            {
                new Category_View(),
                new Category_View(),
                new Category_View()
            };

IList<F> ListResult = new List<F>();

ListResult = (IList<F>) (from r in c select new {r.CalendarID}).Select(f => new F(f.CalendarID));}

Hi shabbir,

The DbSet<TEntity> is in the entity framework assembly, it bases on the DbContext. You can’t convert your class or normal collection to DbSet<TEntity>

# Using Repository Pattern in Entity Framework

http://blogs.msdn.com/b/wriju/archive/2013/08/23/using-repository-pattern-in-entity-framework.aspx

On the other hand, this issue is not related to original issue, please create a new thread for the new issue.

Best Regards

Starain

shabbir_215

shabbir_215

If I am understanding you. just convert it back to DbSet by implementing inversion converter. You have to implement to converters.

private static UDbSetTypeEntity
ConvertToEntity(DomainModel entity)
       
{

            return new
UDbSetTypeEntity

           
{

                CalendarID
= entity.CalendarID,
               
CategoryID
= entity.CategoryID,
               
CategoryName
= entity.CategoryName, ID= entity.ID,
               
Title = entity.Title
           
};

        }

It is extension methods so that how to use. It is associated with object.

var category = new Category();

var item = category.ConvertToEntity()