4

I have a C# function in which I would like to call/run some JavaScript:

protected void DetailsView1_DataBound(object sender, EventArgs e) {
   ...
   // call/run JavaScript
   ...
}

I'm dealing with a form, specifically, submitting the form. Upon clicking "Submit", several C# functions run that take care of validation and other miscellaneous tasks. After these are done, I need to run some JavaScript but I'm having trouble synchronizing these events. The JavaScript is:

...
if (uploader.total.uploaded == 0) {
   if (uploader.files.length > 0) {
      uploader.start();
   }
   e.preventDefault();
}
...

The way I've been trying to do this is by detecting the click event on the "Submit" button via jQuery and running my Javascript, but then the form itself doesn't submit. I've tried variations of this but I haven't had luck.

So how would I accomplish this? Is "RegisterClientScript" something that I should look into? If so, would a possible solution be registering the JavaScript on PageLoad and attaching it to the Submit button? If so, how would I do this in code?

Let me know if I need to further clarify my question.

UPDATE

A bit of clarification... the form on this page is submitted by a button:

<asp:CommandField ValidationGroup="request" ButtonType="Image" 
        CancelText="Reset" CancelImageUrl="../images/internal/btn_reset.gif"
        InsertImageUrl="../images/internal/btn_insert.gif" ShowEditButton="True" 
        ShowInsertButton="True" />

This creates 2 buttons, the Insert being the Submission button so I refer to it as the Submit button.

Thanks,
Hristo

6
  • C# can't "run" Javascript because that is client-side script and C# runs on the server-side. If you register a client-script, it won't execute until the server gives a full response. That's the web. Commented Dec 16, 2010 at 19:08
  • Darn. So how would I solve my problem? Commented Dec 16, 2010 at 19:09
  • Can C# run Java?? Can C# run COBOL??? Can English talk Spanish??? Commented Dec 16, 2010 at 19:25
  • @Hristo I can't answer without further clarification. What does this Javascript do? What does C# need to do before/after the Javascript executes? Commented Dec 16, 2010 at 19:36
  • @Josh... if you look at my Update, clicking that button triggers C# functions that take care of submitting the form (adding to the database, saving info on the server, etc...). In addition to that, I also need to upload files to the servers, which is what the JavaScript does. So I need to figure out a way to upload these files after the user clicks Submit button Commented Dec 16, 2010 at 19:49

7 Answers 7

1

See this in the FAQ:

http://forums.asp.net/t/1360420.aspx#_How_to_register

private void Button2_Click(object sender, System.EventArgs e)
{
    string str;
    str="<script language='JavaScript'>";   
    str+="selectRange()";
    str+="<script>";
    Literal1.Text=str;
}

The main disadvantage to ASP.NET WebForms is that you have to buy into the WebForm model--which is do all logic in C# and let WebForms handle the JavaScript for you. That is why you have to resort to contortions like the FAQ tells you. WebForms is designed to make your web application to be implemented like a desktop application--and that doesn't always work out too well.

The main advantage to ASP.NET MVC is that you have complete control over the markup, JavaScript, etc. Of course the disadvantage is you lose access to all the rich content controls you had with WebForms. However, MVC better matches web programming on most other platforms.

Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately, I can't make the switch because its not my decision. I'm just trying to make things work with the existing, crappy, structure.
1

Yes. You should use RegisterStartupScript.

Code like this should work on your Click handler:

ClientScriptManager scriptManager = Page.ClientScript;
Type type = this.GetType();
string script = "<script type=text/javascript> callMyFunction(); </script>";

scriptManager.RegisterStartupScript(type, "MyName", script);

After the code above execudes, your code-behind will continue execution, "passing the control" over to C#, as you want it to.

Beside function calls, you can also register them using this, just pass the function definition instead of calling it.

3 Comments

@Hristo Oh, I thought you wanted to run this code when a button was clicked. Anyway, it should work wherever you put it, as long as it is on the page.
.. Thanks. A few questions... what is Type type = this.GetType(); and what does the last line do?
@Hristo That's the type of the startup script to register. The last line will add your script to the page. If you put a function call on your script, it'll run the function. Try calling alert('Hi!') with the above example.
0

I am using jquery to submit the form to controller..

here is the code I use.. let me know if you have any questions..

 $(function () {
        $('#form2').submit(function () {
            if ($("#txtServiceTypeCategoryName").val() == "") {
                alert("Please Enter Service Type Category Name");
                return false;
            }
            if ($("#txtServiceTypeCategoryDescription").val() == "") {
                alert("Please Enter Service Type Category Description");
                return false;
            }
            $('#someHiddenDiv1').show();
            $('#CCSave').attr('disabled', 'disabled');
            $('#btnExist').attr('disabled', 'disabled');
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    $('#someHiddenDiv1').hide();
                    $('#CCSave').removeAttr('disabled');
                    $('#btnExist').removeAttr('disabled');
                    window.location.href = '/ServiceTypeCategory/edit/' + $("#txtServiceTypeCategoryID").val();                  
                    //alert('ServiceTypeCategoryChanges Made Successfully!');
                }
            });
            return false;
        });
    });

Comments

0

If you use jQuery you could simply catch the form submission from a "submit" button like so:

$("form").submit(function() {//do something, return true;}

the "return true;" will force the form to submit. If you return false (validation fails or something) the form will not submit.

1 Comment

That works partially in my situation. I catch the event and my js runs, but then the form isn't submitted so I have to click the Submit button again for the actual submission to happen. I've already tried the $('form').submit(); after catching the event and running my code. No luck.
0

It sounds that you don't want the click on the submit button to trigger a server-side request, but rather to be handled on the client. In this case, replace you submit button by a regular button, and tie up the onclick event to the JavaScript code.

Here's how you could do it

document.myform.mybutton.onclick(function(){ //your code here});

2 Comments

Then how would I transfer control back to C# so that the form submits properly?
I'm not sure of what you're trying to do, but you can submit a form using JavaScript with document.myform.submit(); . Do that after you've executed your JavaScript code.
0

An example could be:

protected void DetailsView1_DataBound(object sender, EventArgs e)
{
    ...
    // Example JavaScript
    Response.Write("<script language='javascript'> { window.close();}</script>");
    ...
}

I'm not entirely sure if this is what you want but I've used this before.

Comments

0

As you alluded to you'll want to use RegisterClientScriptBlock or for ajax something like this: ScriptManager.RegisterStartupScript(this, this.GetType(), "MyFunc", "MyFunc();", true);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.