asp.net mvc and webforms use two button - c#

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

Related

How do I update an element on my page with a callback?

I have a element on my page that looks like this
<td><span class="badge badge-danger">Stopped</span></td>
and I want to update it based on things that are going on in the code.
Take this example.. I have a button and that element, and when I click that button I want to start downloading a list of names. Once it's started I want the text inside that span to say "Started" rather than "Stopped" and than once the code finished running aka the list of names has been downloaded, I want it to say "Done" rather than "Started"
And I've been reading back and forth about how to do this and it seems as if I need to implement ajax somehow and I'm not sure how to.
I guess the button would invoke a asp-action="StartDownload" and then it would look something like this..
public ActionResult StartDownload()
{
StartDownload();
return View("WhereSpanIs");
}
private void StartDownload()
{
//Set span text to "Started" some how
//Finished download
//Set span text to "Done" some how
}
For manipulating HTML in the browser when requested by a controller method as in your approach, you would need something like SignalR to enable communication between the server (i.e. controller) and client (i.e. browser).
As you already found out, it's easier using Ajax to update the text in this case (using JavaScript/JQuery). Like in the following example, you could set the text when the button has been clicked, and when the request is complete:
In the view:
<script type="text/javascript">
// call this method on button click
function startDownload() {
// loading, TODO: update the text)
$.ajax({
type: "GET",
url: '#Url.Action("StartDownload", "Home")',
contentType: "application/json; charset=utf-8",
success: function(data) {/* done, TODO: update the text */ },
error: function() { /* error, TODO: update the text }
});
}
</script>
In the (Home) controller:
public ActionResult StartDownload()
{
// TODO: perform the download
return Json(new {status = "OK"});
}
JSON is used to allow the result to be interpretable in JavaScript, although it is not used in this example.
See the Shopping Cart Tutorial for further information.

jQuery Mobile button is not firing without refresh

I am using jQuery mobile in my project and when I log on to system, then go to change password page, the change action is not firing (no action). But, when I refresh the page, it is firing. Briefly, the button on the page is not working when it is redirected from another page except itself. I have imported .css and .js files correctly in master page. (Generic Handler returns correct values and it is working)
head content:
<script type="text/javascript">
$(document).ready(function () {
$("#changePasswordBtn").click(function () {
$.ajax({
type: "POST",
url: "ChangePasswordHandler.ashx",
data: "oldPassword=" + $("#oldPassword").val() + "&newPassword=" + $("#newPassword").val() + "&reNewPassword=" + $("#reNewPassword").val(),
success: function (msg) {
if (msg == 0) $("#popupText").text("success");
else if (msg == 1) $("#popupText").text("wrong pass");
else if (msg == 2) $("#popupText").text("match error");
else if (msg == 3) $("#popupText").text("fill boxes");
else $("#popupText").text("error");
}
});
})
});
</script>
body content:
<input type="button" id="changePasswordBtn" value="Change Password" data-inline="true" />
I have seen a similar problem in my project. Make sure that you are using different ids for buttons.
If the ids are same then the click event is not attached to the right button.
I got a workaround for this issue by changing the way I load my pages.
I put target="_self" into the href element so it don't load using the # system - this way the javascript loads with the initial page load while navigating from one page to a nother.
I will put the below link on my index.html page that will navigate to my signup.html page.
Signup
NOTE: You will lose the 'fancy' jQuery Mobile page transition feature

Invoke a server side action upon the user pressing the Enter/Return key

Updated
Since I got your very helpful answers to this question so promptly, I have reconsidered the problem. I think I need to break it down into two small requirements, so I am updating the question.
In my ASP.NET MVC 4 application, I need that when the user presses the enter key on the keyboard while the focus is in a specific textbox:
Scenario 1: The appropriate server side action must be called. If the user presses the enter key when the cursor is in a different text box, another action must be called.
Scenario 2: If the user pressed the Enter key on the keyboard while the focus is in any textbox in one of the forms on the current page, the form must be posted back with all the form data (HttpPost) to the action on the controller as specified in the action attribute of that <form>.
How do I accomplish these two scenarios?
$('#idOfTextbox').keypress(function(e) {
if(e.which == 13) {
$.ajax({
//.. Your values go here...
});
}
});
If you want to intercept a submitted form, you can use the ajaxForm plugin. This way, you can have several forms on the page and when a form is submitted, it will make an AJAX call to the action method specified in the form's action attribute. You will then be able to handle the response in the 'success' callback of the ajax call.
element.onkeydown = function(event) {
//do something on keydown (enter is keyCode === 13)
};
You can use javascript or simply put each input in a different <form> with a button type="submit" inside.
You can do it as below:
$('#idOfTextbox').keypress(function(e) {
if(e.which == 13) {
$.ajax({
url: './savedata',//Your method name, that is to be called
type: 'POST',
contentType: 'application/json',//Type of data you want to post
data: JSON.stringify({ obj: sampleobject }),//object of post-object i.e. data being posted
success: function(result) {
//Logic to handle success
}
error: function(){}//Handle error here
}
});
I have given an example to call a method that is on the same controller on whose view you are currently working with..

Doing post back on an ajax toolkit modal popup extender

I use an Ajax Toolkit modal pop-up extender to pop-up a form for collecting information from the user. I intend to send the data collected from the user to the code behind for saving into the database on click of the submit button on that form. I found out, however, that the submit button is not posting back to the saver at all.
I do not want to use any client side coding or a web service.
Is it in any way possible to do post back on a modal pop?
There are two solutions of your problem:
Create form with asp:button in a div, initially set it's display none. At the time of popup just make it visible you can set it's position as your requirement. Then after click on submit button it will behave normally and redirect your page.
It is by using jQuery and Ajax. Create a html form and on submit call a JavaScript function
JavaScript function :-
function on_submit(){
var pageUrl = 'your_page_name.aspx'
$.ajax({
type: "POST",
url: pageUrl + "/your_web_method",
data: '{data1:value1, data2:value2}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
make your success code here
}
});
in C#
[WebMethod]
public static void your_web_method(data1, data2)
{
// your code to store value in database
}

Loading usercontrols on demand under jquery tabs

I have few jquery tabs on a usercontrol that loads a separate user control under each. Each user control is unique. It all works fine right now but the overall page response is too slow. In order to improve performance I am trying to load few user controls under these tabs on demand (that is on click of tab). Possibly without post back... ajaxish.
Can anyone guide me?
I tried to follow this tutorial and this one too but did not have any success. I have attached the code for parent usercontrol.
<ul id="tabs">
<li class="active">Rewards</li>
<li id="liCoupons">Coupons</li>
<li id="liLibrary">Library</li>
<li id="liProducts">Favorite</li>
<li id="liPreferences">Preferences</li></ul><ul id="tabPanes" class="rewardsTabs">
<li>
<div class="wrapper active">
<uc:Rewards ID="wellness" runat="server" />
</div>
</li>
<li id="liCoupons">
<div class="wrapper">
<uc:Coupon runat="server" />
</div>
</li><li id="liLibrary">
<div class="wrapper">
<uc:Library runat="server" />
</div>
</li><li id="liProducts">
<div class="wrapper">
<uc:Products runat="server" />
</div>
</li>
<li>
<div class="wrapper">
<div class="preferences">
<uc:Preferences runat="server"/>
</div>
</div>
</li>
The second link you mentioned should work. You don't need to define any user controls in your markup.
<ul id="tabs">
<li class="active">Rewards</li>
<li id="liCoupons">Coupons</li>
<li id="liLibrary">Library</li>
<li id="liProducts">Favorite</li>
<li id="liPreferences">Preferences</li>
</ul>
<div id="results" class="wrapper"></div>
Each tab click will do an ajax call
$.ajax({
type: "POST",
url: "Default.aspx/WebMetodToCall",
data: data, // I wouldn't prefer passing webmethod name here
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$('#result').html(msg.d);
},
failure: function (msg)
//error
}
});
to the web methods.
[WebMethod]
public static string Rewards()
{
return RenderControl("~/controls/rewardsControl.ascx");
}
[WebMethod]
public static string Coupons()
{
return RenderControl("~/controls/couponsControl.ascx");
}
...
Each method will render only the requested control. Also in your method you can keep or extract the viewstate depending on your needs. After rendering, the webmethod should pass back the html string to be injected into the placeholders.
If you tried this and were successful rendering one control at a time but still seeing slowness then you have some back end issues while getting the data. If your controls are data heavy I would recommend doing some server side caching.
Hope this helps.
Does your user controls rely on post-backs and view-state for there working? It will be relative easy to fetch the user control HTML to be displayed in the tab using AJAX but then post-back on that control will send the entire data to the actual page (that may not have the user control loaded). So the basic outline would be
Track the active tab using hidden variable or view-state.
Load the user control based on active tab in the early page cycle. The best bet would be init stage (not that view-state won't be available here, so you have to store active tab in hidden variable and access it via Request.Forms collection).
Give each user control a ID and it should be different from tab to tab. ID is very important for loading the view-state.
If you get corrupted view-state errors at tab switching then you need to first load the user control for the previous tab and then at later page stage (say load/prerender), unload it and load new user control for active tab.
You can use a placeholder or panel control within each tab pane to load the user control in the correct location.
Needless to say, on change of jquery tab, you need to submit your form using post-back script. After every post-back, you need to have a script to re-initialize tabs and selecting active tab.
For better user experience, put entire thing into an UpdatePanel.
perhaps use an anchor that points to the service defined below. For instance,
<li></li>
/// <summary>
/// Service used by ajax for loading social media content
/// </summary>
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class ControlService
{
/// <summary>
/// Streams html content
/// </summary>
/// <param name="type">type of control</param>
/// <returns>html stream of content</returns>
[OperationContract]
[WebGet(UriTemplate = "Content?cType={cType}")]
public Stream GetContent(string cType)
{
var tw = new StringWriter();
var writer = new Html32TextWriter(tw);
var page = new Page();
var control = page.LoadControl(cType);
control.RenderControl(writer);
writer.Close();
var stream = new MemoryStream(Encoding.UTF8.GetBytes(tw.ToString()));
WebOperationContext.Current.OutgoingResponse.ContentType = "text/html";
WebOperationContext.Current.OutgoingResponse.Headers.Add("Cache-Control", "no-cache");
return stream;
}
}
You will need to make an Ajax call in order to make this.
now you have options to call AJAX:
1 - Call via SOAP web service (ASP AjaxScriptManager referencing will be needed for every web method).
2- Call via WCF Service as the previous answer.
3 - Call via Rest service.
4- Call via Jquery ajax method but the request must going to external page like "Actions.aspx" so when you call your method an HTTPRequest will be made into Actions page then it will have the returned data within its response. $.Ajax(url,data,action,successMethod); // this is the fastest way I tried them all.
Here is what you should to do:
1- on the change tab event call your method by using the appropriate Ajax calling method from the above options.
2- from the success method use the returned data but it's better for you to use eval(data) for the DataTime objects.
here is some example explains how to make this call:
var helper = {
callAjax: function(sentData, successFun) {
jQuery.ajax({
url: "/Actions.aspx",
type: "Get",
data: sentData,
cache: true,
dataType: "json",
success: successFun
});
}
};
helper.callAjax('request=getCities&countryID=' + countryID, function (args) {
var result = eval(args); // this object will contain the returned data
var htmlData = '';
for (var i=0;i<result.length;i++){
// write your HTML code by jQuery like this
htmlData += '<div>' + result[i].title + '</div>';
}
$('#tab3').html(htmlData);
});
now at the Actions.ASPX code use the following:
protected void Page_Load(object sender, EventArgs e)
{
object _return = new
{
error = "",
status = true
};
JavaScriptSerializer _serializer = new JavaScriptSerializer();
if (!Page.IsPostBack)
{
string str = Request.QueryString["request"].ToString();
switch (str.ToLower())
{
case "getcities":
int countryID = Convert.ToInt32(Request.QueryString["countryID"].ToString());
_return = JQueryJson.Core.City.getAllCitiesByCountry(countryID).Select(_city => new
{
id = _city.ID,
title = _city.Name
});
_serializer = new JavaScriptSerializer();
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "text/json";
Response.Write(_serializer.Serialize(_return));
break;
}
// etc........
}
If you adjust it a little with jquery, this should work:
http://blogs.msdn.com/b/sburke/archive/2007/06/13/how-to-make-tab-control-panels-load-on-demand.aspx
Or you just use the asp.net tabs.
You should go for the second link using jquery and webmethod. That way you will actually populate the tabs on demand without making you page heavy.
In my opinion, the fastest solution to your problem (but not necessarily the best long-term) is to wrap all your UserControls in a .aspx page. In this situation, you'd just have to move your parent UserControl markup to a new .aspx page, and call it via AJAX.
Assuming that you called this page something like Menu.aspx, and further assuming that you don't need any data passed into this page (that is, it can track all of its own data internally), your jQuery AJAX call would look something like this:
function GetMenu ($placeholder) {
$.ajax({ type: "POST", contentType: "application/json; charset=utf-8", dataType: "json",
url: "Menu.aspx",
done: function (result) {
$placeholder.html(result.d);
},
fail: function () {
$placeholder.html("Error loading menu.");
}
});
}
Some notes:
done and fail will replace success and error in jQuery 1.8, so any jQuery AJAX you use should plan for this transition.
I wrapped this in a function largely because I prefer to put AJAX calls inside JS classes and functions, and then reference those objects. With a menu, it's unlikely you'd have several different pages loading the same data via AJAX (since this will be on some sort of master page, I'm guessing), but it's always good to get yourself in the habit of doing these things.
Depending on your feelings about tightly-coupled HTML/JavaScript, you could replace $placeholder above with a callback function. Calling that from your the page where your menu resides would look something like:
$(document).ready(function () {
GetMenu(MenuCallback);
});
function MenuCallback(menuHtml) {
$("#menu").html(menuHtml); // I'm assuming the ID of your ul/span/div tag here.
}
Some people (myself included) use the $ prefix to differentiate between JavaScript and jQuery variables. So here, $placeholder is a jQuery variable.
You might be able to re-write this $.ajax call as a type: "GET", which would be a little bit more efficient, but I'm not sure if the UserControls would cause problems in that regard. Normally, if I'm loading an entire .aspx page via AJAX, I use GET instead of POST. You don't have to change much to try it out: just switch out the type property and change result.d to result.
I think the best solution is to implement client call back
http://msdn.microsoft.com/en-us/library/ms178210.aspx
When user clicks on some tab,onclick event calls js func with name of tab as parameter, than that tab calls server code with same parameter.
Than in code you load controls you want depending which tab is clicked.
Now you need to render controls into html and send tham back to js function.
Now you have controls in js function, find where you want to insert code an insert it.
that should work in theory and it is not to complicated :))
an asnwer (not mine) to this question is probably useful to you:
Asynchronous loading of user controls in a page
it states that there are problems with this with needing a form on the user control to post back, but that should be ok to have independent forms with ajax post. you'll have to think about what happens when posting the form(s) on the page, but shouldn't be insurmountable. shouldn't be any reason you couldn't just make it the ashx handler you have mentioned.

Categories

Resources