Friday, January 17, 2014

To call a controller method in MVC from UI with callback to read callback data..

In this example lets review the code to invoke a controller method from UI and get JsonResult back. Based on the output data, we can loop through the records to retrieve the values.

Lets start writing the script to invoke it from View.....


In the above, Url.Action method, first parameter is the method to be invoked within HomeController, which is GetDatafromControllertoDisplay and the next one is the controller name. If any parameter needs to be passed, then pass it as above indicated (as it is done for param1).

Below is the callback method that will return data from the controller.


If multiple rows returned, use foreach statement, to loop through the records.



MVC application - setting up the start page.


To define a start up page of your choice to be loaded in MVC (version 4), follow the steps below.

Navigate to App_Start folder and then click open RouteConfig.cs file





Make sure, your RegisterRoutes method updated as below.
In the above code snippet, default controller is directed to HomeController and action is the page defined to be the default one, in this case it is Index.cshtml.

  Accordingly you can change it to any controller / view

Tuesday, January 14, 2014

Formatting Nullable DateTime to short date.

When it was a datetime variable, which needs formatting to a short date string, it was simple. But recently I had to face a situation where I need to deal with nullable datetime and format it to short date string. Though it was simple, but not as straightforward as it is for a regular datetime variable.

  Lets see some examples on both to diagnose the approach to return values in short date string format.

When we try to format a date time variable to short date string, it looks like

DateTime newDate = DateTime.Now;

To set it to have a display format, then you could write it as,

newDate.ToShortDateString("MM/dd/yyyy");

But if we try to do the same with DateTime?, it will throw an exception. To avoid this, we need to read the Value from DateTime? and convert that to a short date string format.

Here is an example below:

 DateTime? newDate = null;
string finalDate = string.Empty;
finalDate = newDate.HasValue ? newDate.Value.ToShortDateString() :                      DateTime.Now.ToShortDateString();

How to use jQuery within @foreach inside Razor view


In this topic, lets review how to use jQuery in a Razor view within a foreach to loop through model data items and handle their properties.

To achieve that, our first line will be to implement the model that will contain data to be displayed.

    @model IEnumerable<DemoNamespace.Models.TestData>


Once we have the model defined, we can loop through the model and use jQuery to enable / disable a property. This will be handy, when you have dynamically generated id values based on EmpID.

      @if(Model != null)
      {
            foreach (DemoNamespace.Models.TestData items in Model.ToList())
                {
                    @:$('#' + items.EmpID).prop("disabled", false);
                }
        }


Happy coding....

Kendo UI - Select event (Kendo Drop Down List)


In a Kendo UI development, it provides developers with more flexible options and easier approach towards our development needs. Whenever there is a need to trigger an ajax call or set another value within the form or to do any thing dynamic, select event will provide few ways to achieve this. I had implemented this in a regular usage as well as for dynamically generated controls and it comes real handy in those situations.

  Lets see some ways to handle select events for Kendo UI drop down list.

In this code below, I am trying to initialize a drop down list by providing text field, value field and an option label. When it comes to invoking methods, you can define as many as you might need within the Events option.

  Here this example will deal with select event only. This code, invokes SelectionUpdate method on change of a drop down, where we can retrieve data, either through event argument or through jQuery.


In this code snippet below, the same selection change event can be accomplished just by writing your function within the @<text> </text> tags.


Either way, the code gets executed, but depends on individuals comfort level.  Having it within a script tag, will help to gather all the scripts together in a separate file and might help towards easy maintenance.

Monday, January 13, 2014

Few simple and effective usages for jQuery......

jQuery is a powerful tool that can enhance our capabilities to deal with data in a better way. Following are few ways to effectively use jQuery within a given application ( I had used it mostly with MVC style of applications).


To update a value within a span tag.

<span id="testspan"></span>
<script>
$("#testspan").text("updating span tag value");
</script>

When you run the app, span tag will be updated with the new value.

To enable and disable a field in UI using jQuery

<input type="text" id="txtField"/>
  • To disable, just use -  $("#txtField").attr("disabled", "disabled");
  • To enable, $("#txtField").removeAttr("disabled");

To hide and display a field

<input type="text" id="txtField"/>
  • To hide, just use $("#txtField").hide()
  • To display, use $("#txtField").show()
  • To add animation while displaying, try $("#txtField").show("slow")

To check if an element is enabled or disabled

<input type="text" id="sample"/>

jQuery to check enabled / disabled status...

if($('#sample').is(':disabled') == false)
{
    alert("text box is not disabled...");
}

Above line of code will check if it is enabled and if so will given an alert.

To disable a given element

<input type="text" id="sample"/>

$('#sample').prop('disabled', true);

To disable a given element and its children

<div id="divtest">
  <input type="text" value="test" id="text1"/>
   <input type="button" id = "btnTest"/>
</div>

$('#divtest').children().prop('disabled', true);

Above line of code will disable all elements that exists within the div tag.

To check if an element exists

if ($('#dividtest').length > 0)
{
    //element exists
}
else
{
    // no such element exists.
}

To enable a Kendo UI drop down list

A simple usage to enable (or even disable) a given Kendo UI drop down.

$('#kendoddl').data("kendoDropDownList").enable(true);

Similarly, other kendo UI controls can be handled too.

To modify height of a div tag at run time

A very easy and simple way to do this using jQuery is :

<div id="1"></div>
<script>
$("#1").css('height', '400px');
</script>

To know if an element is visible

<div id="1"></div>

<script>
$("#1").is(':visible');
</script>

Sunday, January 12, 2014

Kendo UI drop down - How to force a second drop down to read data source after first drop downs selection event without using Cascading

In this case, lets review the scenario first. I have  a drop down ddl1, on its selection event, I would like to read data source for second drop down ddl2.

In the code below, I will create both the drop downs and give a data source to read initially. For my second drop down, I will pass an empty string to avoid loading data.

Below is the code to define my drop down lists:

  In the first one, I had defined text and value fields along with my controller method, similar to ddl2. But for ddl1, I do not require any input parameters. So when loading the UI, ddl1 will be loaded and I will disable the second one, until it is ready to read and load data.

@(Html.Kendo().DropDownList()
                    .Name("ddl1")
                    .OptionLabel("Select an option for ddl1....")
                    .DataTextField("textvalue") // value to be displayed in the drop down
                    .DataValueField("idvalue")
                    .DataSource(source =>
                    {
                        source.Read(read =>
                        {
                            read.Action("Getddl1Data", "DataLoad");
                        });
                   })
                  .Events(events => {events.Change("Loadddl2");    })
                    )

Script below will disable ddl2 until, I will force it to read.

<script>
var ddlltodisable = $("#ddl2").data("kendoDropDownList");
ddlltodisable.enable(false);
</script>

In my second drop down list, I am passing an empty string to avoid data being read and load for the first time.

@(Html.Kendo().DropDownList()
                    .Name("ddl2")
                    .OptionLabel("Select an option for ddl2....")
                    .DataTextField("textvalue")
                    .DataValueField("idvalue")
                    .DataSource(source =>
                    {
                        source.Read(read =>
                        {
                            read.Action("Getddl2Data", "DataLoad", new { parameter1= "" });
                        });
                   })
 )

Below is the script to enable ddl2 and read data with a parameter value from ddl1.

function Loadddl2() {
        $("#ddl2").data("kendoDropDownList").enable(true); //enable drop down list 2
     
        // force read data source for drop down list 2
        var readddl2= $('#ddl2').data("kendoDropDownList");
        readddl2.dataSource.read({ paramvalue: $('#ddl1').data("kendoDropDownList").value() });        
   }


Lets review the controller methods here...

public class DataLoadController : Controller
{
   
      public JsonResult Getddl1Data()
      {
   
             return someobjectforddl1;
       }

       public JsonResult Getddl2Data(string dropdownvalue)
     {
           if(!(string.IsNullorEmpty(dropdownvalue)))
          {
                     // run the code to retrieve data only when valid input
                     return someobjectforddl2;
           }
      }

}