Home > ASP.NET MVC > ASP.NET # MVC # 7 – Call Method on controller from JavaScript function / Call ASP.NET MVC Controller method from JavaScript function

ASP.NET # MVC # 7 – Call Method on controller from JavaScript function / Call ASP.NET MVC Controller method from JavaScript function

 

Hi Friends,

As We know Asp.net mvc divides the web form in three different parts [Model,View,Controller] , as we saw in Model-View-Controller in our post.

Asp.net mvc  doesn’t provide server side events as in Asp.net , we usually come across the situations where we need to call the server side method from the client side while using Asp.net mvc .

For Example :

1) Call some server side method after selected index change event of a dropdown list.

2) Call Server side method on Change of a radio button.

 

To call the Server side method from the JavaScript we use the $.Ajax(url,[options]) method of Ajax for this you need to have the reference of jquery-1.4.1.min.js , MicrosoftAjax.js , MicrosoftMvcAjax.js  in the view like following references

 <script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

<scriptsrc="../../Scripts/MicrosoftAjax.js"type="text/javascript"></script>

<scriptsrc="../../Scripts/MicrosoftMvcAjax.js"type="text/javascript"></script>

For Example we have a dropdownlist ddlTest and on selected index change event of it we are calling the JavaScript method called onDropdownChange .

 <%=Html.DropDownList("ddlDept", new SelectList(Model.lstEmployee, "Emp_Number", "First_Name", 0), "Select", new { @onchange = "onDropdownChange(this);" })%>

//JavaScript MEthod as follow

image

The $.ajax function accepts firs parameter as URL, where we have supplied value as “Employee/ServerMethodName” ,

it means that this function will call the method server side method ServerMethodName which is in the controller Employee as follows.

public class EmployeeController : Controller
    {

        public void ServerMethodName()
        {
            //Put your logic here
        }

    }

 

For More on Microsoft technologies visit our site Dactolonomy of WebResource

Thanks.

Advertisements
Categories: ASP.NET MVC
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: