Using jQuery with ASP.NET to Submit a Form - c#

I've used jQuery dozens of times with PHP with great success. I'm working on an ASP.NET application and would like to use jQuery in the same manner.
Basically, I've got a masterpage that has the form and a webform that has all the form fields and data. A user can submit the form multiple ways - selection of a drop-down, button, etc. I want to catch all submits and use jQuery to submit the form. While the form is being processed, I want to display a new DIV with some text in it. Finally, I want to replace that div with the new form.
How can I accomplish this with the way that ASP.NET works?

Actually ASP.NET will post-back if you use its built-in JavaScript __doPostBack function. There's no other painless way for doing that.
That means you can use jQuery to handle drop-down lists, buttons or whatever (X)HTML element event and handler's body will invoke __doPostBack.
It's unclear that you want is a full-postback, but a partial one using AJAX.
If you're looking for a solution for sending form values to the server without a full-postback, I believe you've these options:
Callback API: http://msdn.microsoft.com/en-us/library/ms178208.aspx
Page methods, update panels: http://msdn.microsoft.com/en-us/magazine/cc163480.aspx
Anyway, let me give you an advise: ASP.NET works quite different compared to PHP and you'd not try to reproduce some known PHP solutions in ASP.NET. You need to change your mind.
About showing a DIV or anything while something is processed, play with initializeRequest ASP.NET AJAX PageRequestManager:
http://msdn.microsoft.com/en-us/library/bb397460.aspx
But that would depend on what AJAX API you're using, because since Microsoft AJAX will be replaced by jQuery in the next times, I'll need to say that you need to do that in some jQuery approach, like creating some $.ajax wrapper so your code will be able to listen when an asynchronous request is going to be made and you can perform actions by handling that situation like showing a DIV or any loading notice.

In ASP.NET Webforms formposts aren't as easy as they are in php. If you're new in ASP.NET development try http://www.asp.net/mvc. A common framework which allows you to implement TypedViews (ViewModes), simple request to modelbinding, and so on...
mh, sample:
[HttpPost]
public JsonResult Insert(string name, string vorname) // name&vorname filled by $_POST:)
{
var #new = new Person { Name = name, Vorname = vorname }
this.repo.Insert(#new);
return this.Json(new { success = true, newId = #new.Id });
}

Related

How can I respond to events on a page in an ASP.NET MVC app that need to access data within the View?

In my ASP.NET MVC project, I need to dynamically manipulate some html elements when the user makes a couple of selections. I assume this needs to be done in code-behind C# (as opposed to in jquery), because how I respond is using data that is retrieved from a SQL Server database and is part of the View (I don't think jQuery would/could know about this MVC/.NET-specific data).
Specifically, when a user clicks a checkbox on the page, provided a selection has been made from an html-select element, my code needs to spring into action to populate other elements on the page.
The View (.cshtml) is getting the data in a Razor code block like so:
#model WebAppRptScheduler.Models.HomeModel
#using System.Data
#{
DataTable dtUnitReportPairEmailVals = Model.UnitReportPairEmailVals DataTable;
var unitRptPairEmailVals = from x in dtUnitReportPairEmailVals.AsEnumerable()
select new
{
emailAddr = x.Field<string>("EmailAddr")
};
This data comes from the Controller:
DataTable UnitReportPairEmailValsDT = new DataTable();
UnitReportPairEmailValsDT = SQL.ExecuteSQLReturnDataTable(SQL.UnitReportPairEmailQuery, CommandType.Text, null);
model.UnitReportPairEmailVals = UnitReportPairEmailValsDT;
Does this (event handling) code belong in the Controller? If so, how is the method declared/decorated so that there is a connection between it and the html elements whose events it needs to monitor?
This is what needs to happen:
User selects an option from an html select
User clicks a checkbox
The code determines that both an option has been selected, and a checkbox checked; it then uses the data to populate other controls, something like this:
#if (unitRptPairEmailVals.Count > 0)
{
email1.Text = unitRptPairEmailVals[0];
}
#if (unitRptPairEmailVals.Count > 1)
{
email2.Text = unitRptPairEmailVals[1];
}
#if (unitRptPairEmailVals.Count > 2)
{
email3.Text = unitRptPairEmailVals[2];
}
The above would populate the text/value of these html inputs:
<label class="margin4horizontal">Email 1</label><input type="text" name="email1" id="email1" />
<label class="margin4horizontal">Email 2</label><input type="text" name="email2" id="email2" />
<label class="margin4horizontal">Email 3</label><input type="text" name="email3" id="email3" />
BTW, if I'm barking up the wrong tree, or am even in the wrong forest altogether, please let me know what the preferred approach is.
UPDATE
Once I pieced together several different answers to this and related questions, I wrote up a tip on how to do this here.
Update: I was answering on mobile last night, and here is a clearer edit and some sample code...
Asp.net MVC has controllers, which contain actions. When you navigation to a URL (HTTP GET), ASP.net translates this via routes into a specific controller action to invoke, then the result of that action is sent back to the browser as plain HTML.
Also when you submit a form (HTTP POST) to specific URL it translates to invoking a controller action via routes. and a ModelBinder will read the body of that HTTP POST and converts it into your Model class. Unlike the classic web forms that used ViewState to track page controls, state, and events.
What you want to achieve can be done in 2 different ways...
Using JavaScript and JQuery. You can issue an Ajax request (GET, POST, etc) to a URL that exists in your ASP.net MVC routes table to execute an action and the results will be returned back to your JavaScript without navigating to another page.
Posting an HTML Form back to the server will allow ASP.net MVC to read the new/changed values in your HTML controls and pass those new values to the controller action, which in turn can render the same view again with the new values and behaviour.

Code in C# that creates redirect buttons in HTML

I am trying to create a C# string builder that will later build an html page based on information in a database and user input.
What I am having trouble with is creating two buttons in the string where one button redirects to page a.asp and the other button redirects to b.asp
I have tried multiple methods but none seem to work. Here is my latest version of code but I might be way off track:
in my page.asp.cs file:
responseString +=
"<div>"
+"<table><tr>"
+"<td><button id='submitSave' type='submit'>Save</button></td>"
+ "<td><button id='continueBatch' onserverclick=\"OnClickButton\" type='submit' runat'server'>Continue Batch</button></td>"
+ "<td><button id='submitDelete' onclick='confirmDialog()' type='button'>Delete</button></td>"
+ "</tr></table></div>";
and it points to the method also in page.asp.cs:
public void OnClickButton()
{
//Redirect to New
Response.Redirect(String.Format("New.aspx?fmtypeP={0}&formverP={1}", FormTypeS, FormVersionS));
}
and last but not least I have in the page.asp page the following:
<form action="save.aspx" method="POST">
I know the form action will need to change but I just wanted to let you know I currently had it in place.
Am I working in the right direction? Is there an easier way to accomplish my task? If not what am I doing wrong?
I would rely on ajax to solve this problem if possible. One solution would be to use onclick and call an existing javascript method like you seem to have done for the confirmDialog() on the delete button. Maybe use jquery's wrapper for the ajax call: http://api.jquery.com/jquery.ajax/. Let the server method return the redirect link and use window.location = the return value in the success-method.
Or if you know what the redirect links should be when building the string you can make the redirect directly: onclick='window.location = "your redirect link"'
You can not use server-side controls like that. In your code they just added to response stream and not being compile and stuff. You need to add controls to your aspx page or add them in code like actual controls via new(), not like strings.

How to do validation before form is submitted on client side in ASP.NET

I have an ASP.NET web form with validators that are disabled. I want to enable validators only AFTER Submit button is clicked and based on if the control is visible or not.
Here is my function:
protected void Submit_Click(object sender, System.EventArgs e)
{
if (ddlSite.Visible){
rfvSite.Enabled = true;
base.Validate();
} else {
rfvSite.Enabled = false;
}
The above code is working fine. But now I want to check if page is valid or not. If the page is Valid then I want to process the form. I don't know how to do this.
You have multiple options:
Try to split your controls into multiple validation groups, which will only validate the controls in a specific group upon submit.
Write your own custom validator. A custom validator can declare a client validation function and a server validation function. Creating a custom validator is well-documented.
As StevieB mentioned, if you hide the controls server-side, the validators won't be fired. If the decision to hide them is made on the client, that's more difficult.
Hook into the client-side validation functions and manipulate the validators. This can be difficult and may require changing internal ASP.Net scripts. Sometimes it's the only way to make web form validation do what you need it to. See this question for an example of extending/modifying validator behavior.
Since I'm new to asp.Net c#, I was wondering is someone can give me an
example or idea as how to achieve this?
Consider using ASP.Net MVC instead of web forms. The web forms model is old and "fights" you on tasks like this. If you are just starting out, I'd suggest at least investigating MVC and see if your time is better spent.
A lot of jquery plugins was created for this reason :
http://tinyurl.com/qetudk8
I believe if you add a
if(Page.IsValid) {
// Code here
}
around the button that is submitting the form, the page should fire off validation errors.

HTML and jQuery Information Passing Design

I am designing a webapp using ASP.NET and jQuery and I could use some advice.
Currently, the ASP.NET page renders an unknown number of elements that perform an action when clicked. Javascript on the front-end handles the click event based on which specific element was selected.
Each element is embedded with information that the javascript function requires. This informaion is added as extra attributes. So for example, a given element might look like
Link 123
jQuery then attaches a click event and uses the extrainformation attribute as a parameter for an internal function. Each element has 3-5 parameters.
This works great, but I have heard recently that it might not be best practice since it is not WC3 compliant. One possible solution would be for each element to directly call the internal javascript function with the necessary parameters. However this makes me uncomfortable because I lose the separation of concerns between rendering the page and executing the client-side logic.
Is there a better way to do this? Or maybe I'm just overthinking it?
Yes there is a better way, its called HTML5 Data Attributes you can access them from jQuery using the $.data() interface.
For Example:
//instead of
Link 123
//use
Link 123
//then access it like
var info = $('#123').data('info');
alert(info); //alerts: 'something important'
Basically anything starting with data- is stored as data about that element in the DOM, jQuery can access this data via the $.data() function.

How can I set a variable in my pages javascript based on my controller action in ASP.NET MVC?

So, I have a page that looks like the following:
alt text http://img704.imageshack.us/img704/5973/croppercapture3.png
This is my basic messaging inbox. I have 2 pages right now, Inbox and Sent (there will eventually be others). These both share the same View, and just have 2 different actions to populate the appropriate data.
The elements on the right-hand side (the message list) is a partial view which has its data populated based on my two controller actions Inbox(int? page) and Sent(int? Page).
So, I have one view "MessageView" and one partial view "MessageList" shared between Inbox/Sent.
However, I now have to get those arrow buttons ("<" ">") working using Ajax. I know how to use jQueries ajax calls well enough, and I know how to render the result of the action call (which returns a partial view).
The problem comes from the fact that the javascript that makes these pagination ajax calls needs to know two things:
What the current page is (whether it be /messages/inbox or /messages/sent)
What the current page is (specified in the query string, ie /messages/inbox?page=2).
Without knowing which page I'm on (Inbox or Sent), it wont know which url to make the ajax call on. Should it make the postback to /messages/inbox or to /messages/sent?
If I wasn't making these messages load with Ajax it would be as simple as loading the appropriate url into the link tags for the "<" and the ">" buttons. But I can't, because part of my requirements states that it must load the messages below without visibly refreshing to a new page.
In JavaScript you can check window.location.pathname to see the pathname section of the current’s page’s URL.
window.location.search gives you the query string.
When the user clicks the Inbox or Sent buttons, you need to rewrite the URLs in your arrows so that they point to the right place.

Categories

Resources