Introduction
This tip shows how to easily run a function in C# from the view using Ajax/jquery.
Background
Created instate of the code of Faroog. His example was 5 years old and not working in VS 2013.
Reference: http://www.codeproject.com/Articles/41828/JQuery-AJAX-with-ASP-NET-MVC
I made it a little more simple.
BUT all credits and honor to Faroog.
Basic Understanding
We uses the URL routing with his parameters to get from view to code behind.
Example
Example is vs2013(u4) project.
New mvc razor project has the following code in it. It is clean and simple.
Using the Code
Make a new mvc razor project,
In the home/index.chtml:
Example 1
Textbox and a button and a result:
<div>
<input type="text" id="valueField" />
<input type="button" id="btnSubmit"
value="Url with parameter" onclick="UrlWParameter();" />
<br /> <br />
Result <div id="Result"></div>
</div>
Jquery, we make a function UrlWParameter
:
<script type="text/javascript">
function UrlWParameter() {
var URL = "/myCS/GetValue/" + $("#valueField").val();
$.get(URL, function (data) {
alert(data);
$("#Result").html(data);
});
}
</script>
In the controllerfolder, create myCSController.cs:
public ActionResult GetValue(string id)
{
Response.Write(id);
return null;
}
RUN the project and you get the answer returned in the alert and result
Example 2
Textbox
and a button
and a result:
<div>
<input type="text" id="valueField" />
<input type="button" id="btn2Submit"
value="Url Separate parameter" onclick="UrlSepParameter();" />
<br /> <br />
Result <div id="Result"></div>
</div>
Jquery, we make a function UrlSepParameter
:
-- sepValue
will be the transfer name to catch in the controller(as shown):
<script type="text/javascript">
function UrlSepParameter() {
var URL = "/myCS/GetSepValue/";
$.get(URL, { sepValue: $("#valueField").val() }, function (data) {
alert(data);
$("#Result").html(data);
});
}
</script>
In the controllerfolder, create myCSController.cs:
public ActionResult GetSepValue(string sepValue)
{
Response.Write(sepValue);
return null;
}
RUN the project and you get the answer returned in the alert and result.
A combination of those two.
Example 3
Textbox
and a button
and a result:
<div>
<input type="text" id="valueField" />
<input type="button" id="btn4Submit"
value="Url both parameter" onclick="UrlBothParameter();" />
<br /> <br />
Result <div id="Result"></div>
</div>
Jquery, we make a function UrlSepParameter
:
-- sepValue
will be the transfer name to catch in the controller (as shown):
<script type="text/javascript">
function UrlBothParameter() {
var URL = "/myCS/GetBothValue/" + $("#valueField").val();
$.get(URL, { sepValue: $("#valueField").val() }, function (data) {
alert(data);
$("#Result").html(data);
});
}
</script>
In the controllerfolder, create myCSController.cs:
public ActionResult GetBothValue(string id, string sepValue)
{
Response.Write(id + "," +sepValue);
return null;
}
RUN the project and you get the two answers returned in the alert and result.
Good luck!
Dinand