Trigger event in MVC Framework - c#

As you've known, it's very easy to trigger an event in WebForm, but it's a problem in MVC Framework. For example, I have 2 DropDownList, Country and State. I want to load the data in State base on selected Country. In WebForm, I can trigger the SelectedIndexChange event, but in MVC Framework, what should I do?
Please help. Thanks in advance.

In WebForm, I can trigger the SelectedIndexChange event, but in MVC
Framework, what should I do?
You could use javascript and subscribe to the onchange javascript event of the dropdown.
For example if you use jQuery:
<script type="text/javascript">
$(function() {
$('#id_of_your_drop_down').on('change', function() {
// the value of the dropdown changed. Here you could do whatever
// you intended to do. For example you could send the selected value
// to a controller action using an AJAX call.
var selectedValue = $(this).val();
var url = '#Url.Action("SomeAction")';
$.post(url, { value: selectedValue }, function(result) {
// The AJAX request completed successfully. Here you could
// do something with the results returned by the server
});
});
});
</script>

Related

How do I create a button's onclick in code behind in mvc

I want to have a onclick event in the my code behind in the controller class of my code but how do I do this with mvc. I can't find anything on google all I've found is for button type submit but I don't want a button of type submit.
This is my button in my view:
<button type="button" id="game" onclick="">
</button>
If you are looking for an ASP.NET web forms Server side events behavior, you will have to create it yourself.
You CAN do (easily) an Ajax call to a controller, get a response and do what ever you want with it. More information Here.
Small example of attaching client side (javascript) onclick event to your button, that calls a controller action on the server and show the results in the console. you need to change this line
#Html.ActionLink("Controller", "Action")
with your controller and action names.
<script type="text/jscript">
$('#game').click(function () {
var url = '#Html.ActionLink("*Controller*", "*Action*")';
$.get(url, null, function (data) {
console.log(data);
/// Add javascript code here to execute when you get the answer from the controller
});
})
</script>
Onclick is a javascript event. You can't react from your mvc controller to it directly. If you need to react to anything that happens on the client, you have to do a postback, either by using a form or using ajax and doing asynchronous request...

Passing value to code behind with jQuery

Need to pass a value from web page to codehind from a hyperlink with a parameter like e.g. page.aspx?id=1. I want to use jQuery if appropriate
How can I pass this value to the code behind without exposing as a querystring in the browser?
One way to do it is to use an ASP.NET hidden field.
<asp:HiddenField id="hdnWhatever" runat="server" value="blah" />
This field can then be manipulated with javascript or jquery and can also be easily used in your codebehind.
Try submitting form as jSON .. Sample -> replace [#form-request] with your form and [/index.php?option=com_seomozapi&task=request.save] with the file action/destination .. return false will keep the focus on current page (no server side refresh)
getScript('//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js', function() {
js = jQuery.noConflict();
js(document).ready(function() {
js('#form-request').submit(function(event) {
console.log('test 1');
$.post('/index.php?option=com_seomozapi&task=request.save'); ?>', $('#form-request').serialize(), function (data, textStatus) {
//Do something here
});
console.log('test 3');
return false;
console.log('test 4');
});
});
});

Executing Server-Side Methods by Clicking on a DIV

I'm working on an ASP.Net project, with C#.
Usually, when I need to put Buttons that will execute some methods, I will use the ASP Controller (Button) inside a runat="server" form.
But I feel that this really limits the capabilities of my website, because when I used to work with JSP, I used jquery to reach a servlet to execute some codes and return a responseText.
I did not check yet how this is done in ASP.Net, but my question concerns controllers and the famous runat="server".
When I add a runat="server" to any HTML Element, I'm supposed to be able to manipulate this HTML element in C# (Server-Side), and this actually works, I can change the ID, set the InnerText or InnerHtml, but the thing that I can't get, is why can't I execute a method by clicking on this element?
The "onclick" attribute is for JavaScript I think, and OnServerClick doesn't seem to work as well. Is it something wrong with my codes? or this doesn't work at all?
You will have to handle the click in the div using the Jquery and call
server-side methods through JQuery
There are several way to execute server side methods by clicking on a div or anything on your page. The first is mentioned __dopostback, second is handling the click in javascript or with jQuery and calling a function in a handler or a page method in a webservice or a page method in your page behind code.
Here is the handler version:
$("#btn1").click(function() {
$.ajax({
url: '/Handler1.ashx?param1=someparam',
success: function(msg, status, xhr) {
//doSomething, manipulate your html
},
error: function() {
//doSomething
}
});
});
I think the second version is better, because you can make a partial postback without any updatepanel, asyncronously. The drawback is, the server side code is separated from your page behind code.
Handler:
public class Handler1: IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
var param1= context.Request.QueryString["param1"];
//param1 value will be "someparam"
// do something cool like filling a datatable serialize it with newtonsoft jsonconvert
var dt= new DataTable();
// fill it
context.Response.Write(JsonConvert.SerializeObject(dt));
}
}
If everything is cool, you get the response in the ajax call in the success section, and the parameter called "msg" will be your serialized JSON datatable.
You can execute a method from jquery click in server, using __doPostBack javascript function, see this threat for more details How to use __doPostBack()
Add this code in your jquery on div onclick and pass DIv id whcih call click
__doPostBack('__Page', DivID);
On page load add this code
if (IsPostBack)
{
//you will get id of div which called function
string eventargs = Request["__EVENTARGUMENT"];
if (!string.IsNullOrEmpty(eventargs))
{
//call your function
}
}
Make the div runat="server" and id="divName"
in page_Load event in cs:
if (IsPostBack)
{
if (Request["__EVENTARGUMENT"] != null && Request["__EVENTARGUMENT"] == "divClick")
{
//code to run in click event of divName
}
}
divName.Attributes.Add("ondivClick", ClientScript.GetPostBackEventReference(divName, "divClick"));
Hope it helps :)
if you are referring to divs with runat="server" attributes, they don't have onserverclick events, that's why it doesn't work

asp.net mvc and webforms use two button

My problem is I'm trying do something to on mvc webforms
page name = addition.aspx
event = button1_click
int numberOne = convert.toint32(textbox1.text);
int numberTwo = convert.toint32(textbox2.text);
int myResult = numberOne + numberTwo;
label1.text = myResult.Tostring();
.
page name = addition.aspx (same page)
event = button2_click
int numberthree = convert.toint32(textbox3.text);
int numberfour = convert.toint32(textbox4.text);
int myResult2 = numberOne + numberTwo;
label2.text = myResult2.Tostring();
my question is I want to do sameting for MVC ( where is event ... i guess i have to conversion on the page post and page get ... am i wrong)
You don't have server side controls for MVC. If you are wanting to have two buttons trigger different events you have a couple options. JQuery is included in your MVC project by default, and it's very popular. So I will show you some examples with that.
Create the two submit buttons to toggle the form action before submit.
Example using jquery:
HTML
<form action="">
<input type="submit" id="first" value="first" />
<input type="submit" id="second" value="second" />
</form>
JS
$(function(){
// on document ready wire up click events
// handle click event for first button
$('#first').on('click', function(){
$('form').prop('action', 'PostActionOne'); // set the action on the form to handle first button post
});
// handle click event for second button
$('#second').on('click', function(){
$('form').prop('action', 'PostActionTwo'); // set the action on the form to handle second button post
});
});
Another option:
Use two buttons with a click event that executes an ajax request to handle the scenario.
HTML
JS
$(function(){
// on document ready wire up click events
$('#first').on('click', function(){
$.ajax({
type: 'POST',
url: 'PostActionOne,
data: data,
success: success,
dataType: dataType
});
});
$('#second').on('click', function(){
$.ajax({
type: 'POST',
url: 'PostActionTwo,
data: data,
success: success,
dataType: dataType
});
});
});
ASP.NET WebPages indeed may offer better event driven programming(arguably), but nevertheless it does not run on the client side. So regardless if you use WebForms or MVC if you want something to take place on the click event of a button located on a browser webpage, make the triggers in javascript, jquery, and use ajax so you don`t have to reload the entire page each time.
Also in mvc you have a helper called
#Ajax.ActionLink("linkname", "Action", "etc");
that can get you working pretty fast, just read about it.
http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxextensions.actionlink%28v=vs.108%29.aspx

JavaScript code to refresh page and or telerik grid

I need some kind of code which will refresh the page every 5min and if not the page then just the Telerik grid displayed on it since that's all that's rly needed.
Only other thing would be if it was after 5min of no activity on the page if possible but it's not core feature.
One possibility is to use a meta refresh tag:
<meta http-equiv="refresh" content="300" />
Another possibility is to use the window.setInterval method to send periodic AJAX requests to a controller action and update the DOM:
window.setInterval(function() {
// Send an AJAX request to a controller action which will
// return a partial with the grid and update the DOM
$.ajax({
url: '/grid',
success: function(result) {
$('#someGridContainer').html(result);
}
});
}, 300000);
And to implement the idle functionality you could use the jquery idle plugin.
keep it simple, call refreshGrid() function when you need to refresh grid.
function refreshGrid() {
if ($(".t-grid .t-refresh").exists()) {
$(".t-grid .t-refresh").trigger('click');
}
}
/*return true if does selected element exist.*/
(function ($) {
$.fn.exists = function () { return jQuery(this).length > 0; }
})(jQuery);
setTimeout(function(){
window.location.reload();
},300000);
If your grid is set up for ajax refreshes, then you can use something like
<script type="text/javascript">
$(function() {
setInterval(function() {
$('#GridName').data('tGrid').ajaxRequest();
}, 300000);
});
</script>
For Server Bindings Telerik Grid Just need to do the following Thing..... Just use and cheers
After any event you can call this
var href = $('.t-refresh').attr('href');
window.location.href = href;
If you are using Ajax or Webservice binding on the Telerik Grid, you can call the rebind() method on the grid object. That will force it to call the Select method of the binding again to get the latest data.
If you combine the rebind() call with Darin's answer of using the SetInterval method, it should give you what you are after.

Categories

Resources