Showing posts with label asp.net. Show all posts
Showing posts with label asp.net. Show all posts

How to call Asp.Net MVC controller action method using JQuery

In this article i  am going to explain how to call controller actions using JQuery in Asp.Net MVC.

Get data from MVC Controller action method:


You can either use $.get or $.ajax functions to call mvc controller action methods using Jquery.

Example:

Assume you have following mvc controller and action method.

public class EmployeeController : Controller
    {
        public string GetEmployee()
        {
            var emp = new Employee() { Id = 1, Name = "John", Designation = "SE" };
            return Newtonsoft.Json.JsonConvert.SerializeObject(emp);
        }
    }

Above Employee Controller has one action method i.e., GetEmployee() which is returning serialized Employee data.

Now use the following JQuery code to call the above mvc action method

Method 1: Using $.get()

$.get("/Employee/GetEmployee", function (data) {
        var employee = JSON.parse(data);
        alert(employee.Name);
    });

Method 2: Using $.ajax()

$.ajax({
        url: "/Employee/GetEmployee",
        success: function (data) {
            var employee = JSON.parse(data);
            alert(employee.Name);
        }
    });

Note: I am using JSON.parse because controller action is returning serialized data. So we have to parse it to convert that to normal object.

Post data to MVC controller action methods using JQuery:


Using POST we can submit the data to controller actions.

Assume you have following controller action which saves the submitted data to database.

[HttpPost]
public bool SaveEmployee(Employee employee)
        {
            //your code to save employee to database
            //return true if data saved succesfully
         
            return true;
        }

Now use the following JQuery code to post data to controller action method.

Method 1: Using $.post()

//create the employee object
var employee = { Name: "Dave", Id: 2, Designation: "Sales" };

    $.post("Employee/SaveEmployee", employee, function (data) {
        if (data == "True") { //change condition based on your return type
            alert("Employee Saved succesfully");
        }
    });

Method 2: Using $.ajax()

//create the employee object
var employee = { Name: "Dave", Id: 2, Designation: "Sales" };

    $.ajax({
        url: "/Employee/SaveEmployee",
        type: "POST",
        data: employee,
        success: function (data) {
            if(data == "True") //change condition based on your return type
            alert("Employee Saved");
        }
    });

In this way we call Asp.Net MVC controller actions using JQuery.

For more posts on JQuery Visit: JQuery


Read more...

Using CDN Bundle Config in ASP.NET MVC

This article explains how to use CDN in MVC script bundles.

Bundling is a technique used in ASP.NET 4.5 to improve request load time. This technique improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript).

If you are using libraries like JQuery, AngularJS in your application, instead of loading them from your own server you can use the CDN url of these libraries. So, when you run your application in production environment these files will be loaded from CDN itself. If the CDN is not available then these files will be loaded from your server.

How to add CDN in MVC bundles:


First of all enable cdn feature (by default it is set to false).

bundles.UseCdn = true;

 Then add your library (JQuery or AngularJS or any other) bundle from CDN. In my example am using JQuery library

var jqueryBundle = new ScriptBundle("~/bundles/jquery", "http://code.jquery.com/jquery-2.0.3.min.js").Include(
                "~/Scripts/jquery-{version}.js");
            jqueryBundle.CdnFallbackExpression = "window.jquery";
            bundles.Add(jqueryBundle);

Use of CdnFallbackExpression is when CDN server is unavailable it loads the file from your server.

In this way we can use CDN in MVC script bundles.

Test CDN bundle in Local Evnironment (Debug Mode):


To test this feature locally you have to run your application in debug="false" mode or you cal also use BundleTable.EnableOptimizations = true;

For more posts on MVC visit : Asp.Net MVC

Read more...

Get Asp.Net TextBox or Label value using JQuery

If you have a Asp.Net TextBox or Label then you can get the value of that textbox/label using Jquery.

Get TextBox value with jquery:


Lets say you have a asp.net textbox like below

<asp:TextBox ID="txtName" runat="server" />

then you can get the value of the above textbox using JQuery using the below code

var name = $("#<%=txtName.ClientID %>").val();

Get Label value with jquery :


Lets say you have a asp.net label like below

<asp:Label ID="lblName" runat="server" Text="codeSolver"/>

then you can get the value of the above label using JQuery using the below code

var name = $("<%=lblName.ClientID %>").html();

Note: If you notice the selector in the above code, we are using "ClientID" to get the value of the control. This is because Asp.Net controls are rendered as html controls in the browser. The "id" will be not same as what you have given to that control.

So if you simply write $("#txtName") it won't work. We use that syntax to get the value of a HTML input(type="text") element.

In this way we can get the Asp.Net TextBox or Label values using JQuery.

For more posts on JQuery visit: JQuery

Read more...

Get Asp.Net TextBox or Label value using JavaScript

If you have a Asp.Net TextBox or Label then you can get the value of that textbox/label using javascript.

Get TextBox value:


Lets say you have a asp.net textbox like below

<asp:TextBox ID="txtName" runat="server" />

then you can get the value of the above textbox using javascript using the below code

var name = document.getElementById("<%=txtName.ClientID %>").value;

Get Label value :


Lets say you have a asp.net label like below

<asp:Label ID="lblName" runat="server" Text="codeSolver"/>

then you can get the value of the above label using javascript using the below code

var name = document.getElementById("<%=lblName.ClientID %>").innerHTML;

Note: If you notice the selector in the above code, we are using "ClientID" to get the value of the control. This is because Asp.Net controls are rendered as html controls in the browser. The "id" will be not same as what you have given to that control.

So if you simply write getElementById("txtName") it won't work. We use that syntax to get the value of a HTML input(type="text") element.

In this way we can get the Asp.Net TextBox or Label values using javascript.

For more posts on Javascript visit: javascript

Read more...

Razor View engine in ASP.NET MVC 4

Razor is the name of the view engine which is introduced by microsoft in mvc3 and they revised it in mvc4. The main use of the view engine is, it processes the ASP.NET content and inserts dynamic content on the browser.

There are two view engines which are maintained by Microsoft.

1 ASPX engine : It works on the <% %> tags and it has important role in the ASP.NET development

2 Razor engine : It works on the regions of content denoted with the @ character.

Let us see the more features of Razor by the following mvc4 application.

Step 1: Create a Empty mvc4 application in Visual Studio and name it as RazorApp.

Step 2: Add a class file to your Model folder and name it as Employee.cs.

now add some properties to our Employee class like below

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace RazorApp.Models

{

    public class Employee

    {

        public int EmployeeID { get; set; }

        public string Name { get; set; }

        public string Designation { get; set; }

        public decimal Salary { get; set; }

    }

}


Step 3: Add a Controller to your application

To add a Controller: Right click on Controller Folder --> select Add --> Select Controller --> Set the name to HomeController --> Select Template as Empty MVC Controller --> and finally click on ADD

Now add the following code to your Controller

using System;

using System.Linq;

using System.Web;

using RazorApp.Models;



namespace RazorApp.Controllers

{
    public class HomeController : Controller

    {
        //Add a Employee

        Employee employee = new Employee
        {
            EmployeeID=1,

            Name="John",

            Designation="Manager",

            Salary=10000M  //decimal representation
        };

        public ActionResult Index()
        {
            return View(employee); //returning our Employee object to View
        }

}


In the above code, We have created a Action method called Index and we populated properties of Employee Object. Also we have passed the Employee to View method so that it is used as the model when the View is rendered.

Step 4: Now we are going to create a View.

To create View Right click on the Index method of your HomeController class --> select Add View --> check the option "Create a strongly-typed view" --> now select Employee class from drop-down list --> Uncheck the "Use layout or master page option" --> finally click on ADD.

Now the newly added View is will appear in the Views/Home folder as Index.cshtml. It will look like

@model RazorApp.Models.Employee

@{

    Layout = null;

}

<!DOCTYPE html>

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

</head>

<body>

    <div>       

    </div>

</body>

</html>


Look at the first line. The @model statement declares the type of the model object thar we are passing to the view from our action method. This statement allows us to use the methods, properties and fields of the view model object through @Model. (Example: To access the Name property of object we have to use @Model.Name)

Now, Change your View to look like the following code.

@model RazorApp.Models.Employee

@{

    Layout = null;

}

<!DOCTYPE html>

<html>

<head>

    <meta name="viewport" content="width=device-width" />

    <title>Index</title>

</head>

<body>

    <div>

        @Model.Name

    </div>

</body>

</html>


 Now run the application and you will see the output as following.




When you type @Model. in your View then the Visual Studio auomatically show the suggestions member names of that particulat Object Model.

And if you want to access the members which are not defined in Emploee class(like @Model.Company) then Visual Studio flag errors.

Now look at the following code in the View

@{
    Layout = null;
}

This is the example of Razor code block. Using this we can include c# statements in a view. The statements written inside this block are executed when a view is rendered.

The above code block is used to se the property of the Layout property to null, wchich means we are not using any layout or master page for this particular application.

This is about Razors and i am going to explain "Creating Layout in MVC4" in my NEXT POST.

Read more...

Create MVC4 Project in Visual Studio 2013

step 1:  Open Visual Studio 2012

step 2:  Select File --> New --> Project

step 3:  Select the language visual Basic/Visual C#/Visual C++ etc., on the left side and Select Asp.Net   MVC4 Application on the right side.


step 4: Give any Name to your application and click on OK.

step 5: Now a small window will open asking to select a template. Choose Empty template so that your   project will not get any default files . And select View Engine as Razor  and click on OK.



This way you can create a mvc4 project in visual studio 2012.

Creating mvc4 application in Visual Studio 2013 :

step 1: Open Visual Studio 2013

step 2: Select File --> New --> Project

step 3: Select the language visual Basic/Visual C#/Visual C++ etc  and on right side select ASP.NET   WebApplication and click on OK.


step 4: Now a small window will open asking to Select a Template, Select MVC there and click on            Create Project.



Thats all.
In this way we can create MVC4 Application in Visual Stuio 2012 and Visual studio 2013.

Read more...

Hyperlink open in new Tab

If you want any page to open in a new tab using html anchor tag you have to include target="_blank" attribute.

Example:

<a href="/http/www.coding-issues.in/content/Name.aspx" target="_blank">Click to open file </a>

Read more...

ExecuteReader in Asp.Net with Example

ExecuteReader is forward only retrieval of records and it is used to read the table values from first to last. It sends the CommandText to the Connection and builds a SqlDataReader.

Example :

Consider you have a " Employees " table in your database.

Now , you want to fetch all the record from your Employee table and show them in a GridView.

Add this code to youe aspx Page(Here i am using a GridView control to show Employee records).

<form id="form1" runat="server">
<asp:GridView ID="EmployeesList" runat="server">
</asp:GridView>
</form>

Write this code in your code behind file(Name.aspx.cs) :

//Add Following NameSpaces

using System;
using System.Data.SqlClient;
using System.Data;

//Add some code to your Page_Load Event

protected void Page_Load(object sender, EventArgs e)
{
if (! IsPostBack) //When you are posting the page for the first time then IsPostBack is false and !IsPostBack it becomes true
{
BindGridview();
}
}

// This method is used to bind gridview from database
protected void BindGridview()
{
using (SqlConnection connection = new SqlConnection("Write Your Connection string here.."))
{
connection.Open();
SqlCommand cmd = new SqlCommand("Select FirstName,LastName FROM Employees", connection);

SqlDataReader reader = cmd.ExecuteReader();
EmployeesList.DataSource = reader; //Adding datasource to our GridView
Employees.DataBind();  //Binding data to GridView
connection.Close();
}
}

In this way you can fetch(retrieve) records from your DataBase table using ExecuteReader  

Read more...

ExecuteNonQuery() in Asp.Net With Example

ExecuteNonQuery executes a SQL command(Insert,Update or Delete commands) against the connection and returns the number of rows affected.

Example :

Consider you have a " Employee " table in your database.

Now , you want to insert a record into your Employee table.

Consider you have to enter two values i.e., FirstName and LastName into your table. For that , write this code into your aspx(Name.aspx) page..

 <form id="form1" runat="server">
        <table>
            <tr>
                <td>FirstName</td>
                <td><asp:TextBox runat="server" ID="txtFirstName"> </asp:TextBox> </td>
            </tr>
            <tr>
                <td>LastName</td>
                <td><asp:TextBox runat="server" ID="txtLastName"> </asp:TextBox></td>
            </tr>
            <tr>
                <td><asp:Button runat="server" ID="btnSubmit" Text="SUBMIT" OnClick="btnSubmit_Click"/>                </td>
                <td></td>
            </tr>
        </table>
 </form>

The above form contains two textboxes to enter FirstName and LastName and a Button to Submit the data.

Note: Note the onClick attribute of Button. The event btnSubmit_Click is called when you click on the button.

In your code behind file(Name.aspx.cs) write this code...


//Add these two namespaces
using System;
using System.Data.SqlClient;

// Add btnSubmit_Click event(which is fired when you click on button) below Page_Load() event..

protected void btnSubmit_Click(object sender, EventArgs e)
{
using (SqlConnection connection=new SqlConnection("Write your connection string here.."))
{
connection.Open();
SqlCommand cmd = new SqlCommand("insert into Employee(FirstName,LastName) values(@FName,@LName)", connection);

//then add parameters to your command

cmd.Parameters.AddWithValue("@FName", txtFirstName.Text());
cmd.Parameters.AddWithValue("@LName", txtLastName.Text());

int result= cmd.ExecuteNonQuery();  //here you will get the no.of rows effected 

if(result > 0)  // It means atleast one row has been effected 
{
response.write("Employee added");
}
else
{
response.write("Error in adding Employee");
}
connection.Close();  //Don't forget to close the connection when you are done with the connection.
}
}

In this way, we can add records to our DataBase table(Using ExecuteNonQuery()..)

Read more...

jQuery click event for dynamically created elements:

After scratching my head for 2-3 hours(before searching it on the internet) on this problem, i got to know the reason why this(.click()) doesn't work on dynamically created elements.

If you want to click on any  element(button/span/div/textbox/.....etc) using jQuery, we can do that by using  this code,

$('selector').click(function(){
//your code
})

This works fine if you have created that element already.

But, if you created your elements dynamically(using javascript), then this code doesn't work.
Because, .click() will attach events to elements that already exists. As you are dynamically creating your elements using javascript, it doesn't work.

For this you have to use some other functions which works on dynamically created elements. This can be done in different ways..

Earlier we have .live() function

$('selector').live('click', function()
{
//your code
});

but .live() is deprecated.This can be replaced by other functions.

 Delegate():

Using delegate() function you can click on dynamically generated HTML elements.

Example:
$(document).delegate('selector', 'click', function()
{
//your code
});

ON():

Using on() function you can click on dynamically generated HTML elements.

Example:
$(document).on('click', 'selector', function()
{
// your code
});

In this way you can click on dynamically generated HTML elements..

For more posts on JQuery visit: JQuery

Read more...

Programmatic DataBinding in Asp.Net


An alternative to declarative databinding, you can programmatically bind any of the List controls to a data source

Example:
Lets create a BulletList which shows the list of Fruits.

<asp:BulletedList
            ID="blFruits"
            runat="server" />

And in Page_Load() event write this code. 

protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            List<String> fruits = new List<string>();
            fruits.Add("Apple");
            fruits.Add("Banana");
            fruits.Add("Mango");
            blFruits.DataSource = fruits;
            blFruits.DataBind();
        }
    }

if(!IsPostBack) prevents the re-initialisation of the BulletList items during postbacks.

Read About Declarative DataBinding : Declarative DataBinding in Asp.Net

Read more...

Declarative DataBinding in Asp.Net


You can bind any of the List controls to a data source. The List controls support both
declarative databinding and programmatic databinding

Example:

Suppose you have a movies table in your database. It has two columns named Id and Title.
<asp:DropDownList
            ID="ddlMovies"
            DataSourceID="srcMovies"
            DataTextField="Title"
            DataValueField="Id"
            runat="server" />

        <asp:SqlDataSource
            ID="srcMovies"
            SelectCommand="SELECT Id, Title FROM Movies"
            ConnectionString="yourConnectionString"
            runat="server" />

The DropDownList control’s DataSourceID property points to the ID of the SqlDataSource control. The SqlDataSource control retrieves the records from the Movies database table. The DropDownList control grabs these records from the SqlDataSource control and creates a ListItem control for each data item. 

The DropDownList control has both its DataTextField and DataValueField properties set. When the DropDownList control creates each of its list items, it uses the values of the DataTextField and DataValueField properties to set the Text and Value properties of each list item.

Read About Programmatic DataBinding :  ProgrammaticDataBinding in Asp.Net

Read more...

Radio Button List in Asp.Net

Radio Button List contains list of Radio Buttons.

Example:
<asp:RadioButtonList
            ID="rblMovies"
            runat="server">
            <asp:ListItem
                Text="The Remains of the Day"
                Value="movie1" />
            <asp:ListItem
                Text="Star Wars"
                Value="movie2" />
            <asp:ListItem
                Text="Pulp Fiction"
                Value="movie3" />
        </asp:RadioButtonList>


Above code contains a RadioButtonList control that contains three ListItem controls that correspond to the three radio buttons. All the List controls use the ListItem control to represent individual list items.

The ListItem control supports the following five properties:

Attributes—Enables you to add HTML attributes to a list item.
Enabled—Enables you to disable a list item.
Selected—Enables you to mark a list item as selected.
Text—Enables you to specify the text displayed by the List Item.
Value—Enables you to specify a hidden value associated with the List Item.
You use the Text property to indicate the text that you want the option to display, and the Value property to indicate a hidden value associated with the option. For example, the hidden value might represent the value of a primary key column in a database table.

The Selected property enables you to show a list item as selected. Selected radio buttons and check boxes appear checked. The selected option in a DropDownList is the default option displayed. Selected options in a ListBox appear highlighted. And in the case of a BulletedList control, the selected property has no effect whatsoever.

The Enabled property has different effects when used with different List controls. When you set a ListItem control’s Enabled property to the value False when using the DropDownList or ListBox controls, the list item is not rendered to the browser. When you use this property with a CheckBoxList, RadioButtonList, or BulletedList control, the list item is ghosted and nonfunctional.
Read more...

DataBinding Expressions in Asp.Net

A DataBinding expression is a special type of expression not evaluated until runtime. You mark a databinding expression in a page by wrapping the expression in opening <%# and closing %> brackets.

A DataBinding expression isn’t evaluated until a control’s DataBinding event is raised.

When you bind a DataBound control to a DataSource control declaratively, this event is raised automatically. When you bind a DataSource control to a data source programmatically, the DataBinding event is raised when you call the DataBind() method.

Example:

Suppose you have a movies table in your database. It has two columns named "Title" and "DateReleased".

<asp:DataList id="DataList1" DataSourceId="srcMovies" Runat="server">
    <ItemTemplate>
    <b>Movie Title:</b> <%#Eval("Title")%>
    <br />
    <b>Date Released:</b> <%#Eval("DateReleased", "{0:D}") %>
    <hr />
    </ItemTemplate>
    </asp:DataList>

<asp:SqlDataSource
id="srcMovies"
ConnectionString="your connection string"
SelectCommand="SELECT Title,DateReleased FROM Movies"
Runat="server" />


The first DataBinding expression displays the title of the movie and the second DataBinding expression displays the date the movie was released. Both DataBinding expressions call the Eval() method. The Eval() method is a protected method of the Page class. Behind the scenes, the Page.Eval() method calls the static
(shared) DataBinder.Eval() method. If you want to be verbose, instead of using the Eval() method, you could use the following two expressions:

<%# DataBinder.Eval(Container.DataItem, “Title”) %>
<%# DataBinder.Eval(Container.DataItem, “DateReleased”, “{0:D}” ) %>

In ASP.NET version 1.x, you had to use DataBinder.Eval() when displaying data items in a template.
You can use <%# FormatTitle(Eval(“Title”)) %>. This method formats each of the titles displayed by the Repeater control by making each title bold and uppercase

Note: Technically, the Eval() method uses reflection when evaluating the data item to find
a property with a certain name. You do pay a performance penalty when you use
reflection.

As an alternative, you can improve the performance of your DataBinding expressions by casting the data items to a particular type like this:

<%# ((System.Data.DataRowView)Container.DataItem)[“Title”] %>

Read more...

RequiredFieldValidator on DropDownList

You can use the RequiredFieldValidator control’s InitialValue property to specify a default value other than an empty string.

The RequiredFieldValidator control includes an InitialValue property. The value of the first list from the DropDownList control is assigned to this property.

Example:

<asp:DropDownList id="dropFavoriteColor" Runat="server">
<asp:ListItem Text="Select Color" Value="none" />
<asp:ListItem Text="Red" Value="Red" />
<asp:ListItem Text="Blue" Value="Blue" />
<asp:ListItem Text="Green" Value="Green" />
</asp:DropDownList>

<asp:RequiredFieldValidator id="reqFavoriteColor" Text="(Required)" InitialValue="none" ControlToValidate="dropFavoriteColor" Runat="server" />

Read more...

FormView: Change Mode of FormView dynamically

FormView :

<asp:FormView runat="server" ID="formViewContactInformation" DataKeyField="ID"  DataSourceID="dsContactInformation"> </asp:FormView>

1. To change the mode of FormView to Edit Mode, you have to call ChangeMode method of FormView and pass the mode.

              formViewContactInformation.ChangeMode(FormViewMode.Edit);

2. To change the mode of FormView to Insert Mode

            formViewContactInformation.ChangeMode(FormViewMode.Insert);

3. To change the mode of FormView to ReadOnly Mode

            formViewContactInformation.ChangeMode(FormViewMode.ReadOnly);


Read more...

Understanding MSIL, CLR and JIT

MSIL = Microsoft Intermediate Language
CLR = Common Language Runtime
JIT = Just In Time compiler

MSIL is the "machine code like" language that the C# compiles your code into.

The CLR is the "machine" that the MSIL runs on.

When runinng the MSIL the CLR converts your code into real machine code using the JIT.

In this context just in time stands for that only the MSIL needed for the moment is beeing compiled into machine code.

The real machine code is run on yor computers actual CPU.
CodeExecution cycle



Read more...

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for 'jquery'. Please add a ScriptResourceMapping named jquery(case-sensitive)

You need a web.config appSetting key to enable the pre 4.5 validation mode.

Specifies how ASP.NET globally enables the built-in validator controls to use unobtrusive JavaScript for client-side validation logic.

Type: UnobtrusiveValidationMode
Default value: None

Remarks: If this key value is set to "None" [default], the ASP.NET application will use the pre-4.5 behavior  JavaScript inline in the pages) for client-side validation logic. If this key value is set to "WebForms",  ASP.NET uses HTML5 data-attributes and late bound JavaScript from an added script reference for client-side validation logic.

Add this to your web.config :
    <appSettings>
      <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
    </appSettings>
Read more...

Using statement in C# (ASP.NET)

When you are dealing with objects in c#, you have to make sure that when you are done with the object, the object's Dispose method is called.

This can be done using try and finally blocks, where you use the object in try Block and destroy the object in finally block. But this can be easily done by "using" statement.

The using statement gets translated into a try and finally block. A using statement is translated into three parts: acquisition, usage, and disposal. The resource is first acquired, then the usage is enclosed in a try statement with a finally clause. The object then gets disposed in the finally clause. For example the following lines of code using the using statement,


Normally in the try catch block we would have written:

SqlConnection con;
try
{
    con=new Sqlconnection(connectionString);
}
catch
{
       //Do Something with the exception..
}
finally
{
    con.close();  //Disposing the object manually.
}

But using block has made this simple(rather to dispose objects manually) :

using(SqlConnection con=new Sqlconnection(connectionString))
{
      con.open();
      //Do Some Operation
}

And now, you dont need to worry about the object's memory release; since using block takes care of it automatically by invoking con.close() and everyother object that is used inside it.. :)

And thus, it helps us in managing the memory in a more efficient way..

Note: One advantage with the using block is that, even in the case if the statements in that block raises an exception, that block disposes the memory.. And thats good of it.. And even we need to look at the cons of it like: what if there is an error while acquiring the source? (like if we use the filestream), in that case we should use using block nested inside the try-catch block... :)


Read more...

Clear all fields in ASP.NET form

You can make use of OnClientClick event. This will reset all all the control present on the form. OnClientClick="this.form.reset();return false;"

See the Code :

<asp:Button ID="Reset_Button" runat="server" Text="Reset"
    Width="81px" OnClientClick="this.form.reset();return false;" />

Read more...