如何在服务器端/后台使用vb.net动态更改Jquery对话框上按钮上的文本?

huangapple go评论58阅读模式
英文:

How do I change dynamically the text on the button on Jquery Dialog on server side/code behind vb.net

问题

Here's the translation of the code portion you provided:

这是我的JavaScript代码,但它没有起作用:

<script>
    $(function openDialog(msg) {
        var stringMessage = msg.text;
        $("#dialog-1").dialog({
            dialogClass: "no-close",
            draggable: false,
            resizable: false,
            closeOnEscape: false,
            modal: true,
            autoOpen: false,
            buttons: [
                {
                    text: stringMessage,
                    click: function() {
                        $(this).dialog("close");
                    }
                }
            ]
        });
        $("#dialog-1").dialog("open");
    });
</script>

这是我的HTML:

<div id="dialog-1" title="警告">  
    <p id="msgWarning" runat="server">Message Here</p>
</div>

这是我在VB.NET中的代码后端:

Dim msg As String = "Exit"
Page.ClientScript.RegisterStartupScript(Me.GetType(), "startDialog", "<script language='javascript'>openDialog('" & msg & "');</script>", True)

请注意,这个翻译中包括代码的内容,不包括问题的回答。

英文:

May I ask for help, I need to change the text of the button of Jquery Dialog from code behind, how can I do this? I know I can just set the button text from the Javascript but depending on the message I'm going to set, it maybe CANCEL, OK, YES, NO. So I would like to know how to dynamically change it. Thank you!

This is my javascript but it's not working:

 &lt;script&gt;
      $(function openDialog(msg) {

         var stringMessage = msg.text;
        $( &quot;#dialog-1&quot; ).dialog({
            dialogClass: &quot;no-close&quot;,
            draggable: false,
            resizable: false,
            closeOnEscape: false,
            modal: true,
            autoOpen: false,
            buttons: [
                {
                    text: stringMessage,
                    click: function() {
                    $( this ).dialog( &quot;close&quot; );
                    }
                }
            ]

        });

        $(&quot;#dialog-1&quot;).dialog(&quot;open&quot;);
     });
&lt;/script&gt;

This is my html:

&lt;div id = &quot;dialog-1&quot; title = &quot;Warning&quot; &gt;  
    &lt;p id=&quot;msgWarning&quot; runat=&quot;server&quot; &gt;Message Here&lt;/p&gt;
&lt;/div&gt;

This is my code behind on vb.net:

Dim msg As String = &quot;Exit&quot;
Page.ClientScript.RegisterStartupScript(Me.GetType(), &quot;startDialog&quot;, &quot;&lt;script language=&#39;javascript&#39;&gt;openDialog(&#39;&quot; &amp; msg &amp; &quot;&#39;);&lt;/script&gt;&quot;, True)

答案1

得分: 1

以下是您的代码的翻译:

Say your server side code is this:
如果您的服务器端代码如下

Protected Sub cmdTest_Click(sender As Object, e As EventArgs)
    Call MyDialog("My Title",
        "Delete this file&lt;br/&gt;&lt;i&gt;(This cannot be un-done)&lt;/i&gt;",
        "Ok", "Cancel")
End Sub

Sub MyDialog(sTitle As String,
             sBody As String,
             sOkText As String,
             sCancelText As String)

    Dim strJava As String =
        $"mydialog(&#39;{sTitle}&#39;,&#39;{sBody}&#39;,&#39;{sOkText}&#39;,&#39;{sCancelText}&#39;);"

    ScriptManager.RegisterStartupScript(Page, Page.GetType, "MyPop", strJava, True)
End Sub
Ok, so then our markup is this:
好的,接下来是我们的标记:

&lt;asp:Button ID=&quot;cmdTest&quot; runat=&quot;server&quot; Text=&quot;启动/显示对话框 VB 代码&quot; OnClick=&quot;cmdTest_Click&quot; /&gt;

&lt;div id=&quot;DialogArea&quot; style=&quot;display: none&quot;&gt;
    &lt;h4 id=&quot;mybody&quot;&gt;&lt;/h4&gt;
&lt;/div&gt;

&lt;script&gt;
function mydialog(sTitle, sBody, sOkText, sCancelText) {
    myDialog = $("#DialogArea")
    $('#mybody').html(sBody)
    myDialog.dialog({
        title: sTitle,
        modal: true,
        appendTo: "form",
        dialogClass: "myshadow",
        buttons: [
            {
                id: "myOkBtn",
                text: sOkText,
                click: function () {
                    myDialog.dialog('close')
                }
            },
            {
                id: "MyCancel",
                text: sCancelText,
                click: function () {
                    myDialog.dialog('close')
                }
            }
        ]
    })
}
&lt;/script&gt;
And now the result is this:
现在的结果如下:

[![enter image description here][1]][1]

Edit2: Putting this to use for say delete buttons etc.
编辑2:将这个用于删除按钮等操作。

Ok, now that we have a working dialog, the &quot;real&quot; value use is of course in typical button code. Say a delete button, or even a button in a gridview.
好的,现在我们有一个可工作的对话框,当然它的真正价值在于典型的按钮代码中。比如删除按钮,甚至是在网格视图中的按钮。

Let's do an example with a grid view, but even just a plain button on a form will work the same.
让我们用一个网格视图来做一个示例,但即使是在表单上的一个普通按钮也会有相同的效果。

Theory: so, in desktop land, we often have a button, click on it, then prompt to confirm (say a delete option).
理论:在桌面应用程序中,我们经常会有一个按钮,点击它,然后会出现确认提示(比如删除选项)。

In web land? Well, due to the page life cycle and post-back?
在Web应用程序中呢?嗯,由于页面生命周期和回发?

We have to &quot;flip&quot; this backwards so to speak.
我们不得不“反转”这个过程,可以这么说。

As we all know, a plain regular button click in a webform page can be &quot;controlled&quot; by a JavaScript event.
众所周知,在Web表单页面中,一个普通的按钮单击可以通过JavaScript事件“控制”。

So buttons have BOTH a server-side click event and a client-side event.
所以按钮既有服务器端的点击事件,也有客户端的事件。

If the client-side event returns true, then the button runs, and if JavaScript returns false, then the server-side button DOES NOT run.
如果客户端事件返回true,则按钮会运行,如果JavaScript返回false,则服务器端按钮不会运行。

However, ONE extra step and issue has to be dealt with.
然而,必须处理一个额外的步骤和问题。

jQuery.UI, and in fact most JavaScript routines DO NOT halt code. That means this does NOT block or freeze the browser code (it is simply not allowed, or better stated "frowned" upon.
jQuery.UI,实际上大多数JavaScript例程不会停止代码。这意味着这不会阻止或冻结浏览器代码(它只是不允许,或者更准确地说“不被看好”。

What that means is when we run the JS code to pop the dialog, the JS code we just used DOES NOT HALT nor wait.
这意味着当我们运行JS代码来弹出对话框时,我们刚刚使用的JS代码既不会停止也不会等待。

In other words, the call to pop the dialog will run, pop the dialog AND THEN FINISH running!
换句话说,调用弹出对话框的操作将运行,弹出对话框,然后完成运行!

To deal with this issue, we use a bit of a trick:
为了解决这个问题,我们使用了一个小技巧:

We add a true/false flag to our JS code AND WE WILL then click the button again!
我们在JS代码中添加了一个true/false标志,然后我们将再次单击按钮!

So, I first just set up the button click (say to do the delete). I test, get that code working.
所以,我首先只设置按钮点击(比如执行删除操作)。我进行测试,确保代码可以正常工作。

So, say this gridview:
比如说这个网格视图:

```html
&lt;asp:GridView ID=&quot;GridView1&quot; runat=&quot;server&quot; AutoGenerateColumns=&quot;False&quot;
    CssClass=&quot;table table-hover&quot; Width=&quot;45%&quot;
    DataKeyNames=&quot;ID&quot; &gt;
    &lt;Columns&gt;
        &lt;asp:BoundField DataField=&quot;FirstName&quot; HeaderText=&quot;First Name&quot;   /&gt;
        &lt;asp:BoundField DataField=&quot;LastName&quot; HeaderText=&quot;First Name&quot;    /&gt;
        &lt;asp:BoundField DataField=&quot;HotelName&quot

<details>
<summary>英文:</summary>

Say your server side code is this:

    Protected Sub cmdTest_Click(sender As Object, e As EventArgs)

        Call MyDialog(&quot;My Title&quot;,
            &quot;Delete this file&lt;br/&gt;&lt;i&gt;(This cannot be un-done)&lt;/i&gt;&quot;,
            &quot;Ok&quot;, &quot;Cancel&quot;)


    End Sub


    Sub MyDialog(sTitle As String,
                 sBody As String,
                 sOkText As String,
                 sCancelText As String)

        Dim strJava As String =
            $&quot;mydialog(&#39;{sTitle}&#39;,&#39;{sBody}&#39;,&#39;{sOkText}&#39;,&#39;{sCancelText}&#39;);&quot;

        ScriptManager.RegisterStartupScript(Page, Page.GetType, &quot;MyPop&quot;, strJava, True)

    End Sub


Ok, so then our markup is this:

        &lt;asp:Button ID=&quot;cmdTest&quot; runat=&quot;server&quot; Text=&quot;Launch/show dialog VB code&quot;
            OnClick=&quot;cmdTest_Click&quot; /&gt;


        &lt;div id=&quot;DialogArea&quot; style=&quot;display: none&quot;&gt;
            &lt;h4 id=&quot;mybody&quot;&gt;&lt;/h4&gt;
        &lt;/div&gt;


    &lt;script&gt;

        function mydialog(sTitle, sBody, sOkText, sCancelText) {
            myDialog = $(&quot;#DialogArea&quot;)
            $(&#39;#mybody&#39;).html(sBody)
            myDialog.dialog({
                title: sTitle,
                modal: true,
                appendTo: &quot;form&quot;,
                dialogClass: &quot;myshadow&quot;,
                buttons: [
                    {
                        id: &quot;myOkBtn&quot;,
                        text: sOkText,
                        click: function () {
                            myDialog.dialog(&#39;close&#39;)
                        }
                    },
                    {
                        id: &quot;MyCancel&quot;,
                        text: sCancelText,
                        click: function () {
                            myDialog.dialog(&#39;close&#39;)
                        }
                    }
                ]
            })
        }
    &lt;/script&gt;

And now the result is this:

[![enter image description here][1]][1]

Edit2: Putting this to use for say delete buttons etc.
=====

Ok, now that we have a working dialog, the &quot;real&quot; value use is of course in typical button code. Say a delete button, or even a button in a gridview.

Let&#39;s do a example with grid view, but even just a plain button on a form will work the same.

Theory: so, in desktop land, we often have a button, click on it, then prompt to confirm (say a delete option).

In web land? Well, due to the page life cycle and post-back?

We have to &quot;flip&quot; this backwards so to speak.

As we all know, a plain regular button click in a webform page can be &quot;controlled&quot; by a a JavaScript event. 

So buttons have BOTH a server side click event, and a client side event.

If the client side event returns true, then the button runs, and if JavaScript returns false, then the server side button DOES NOT run.

However, ONE extra step and issue has to be dealt with.

jQuery.UI, and in fact most JavaScript routines DO NOT halt code. That means this does NOT block or freeze the browser code (it simple not allowed, or better stated &quot;frowned&quot; upon.

What that means is when we run the js code to pop the dialog, the js code we just used DOES NOT HALT nor wait.

In other words, the call to pop the dialog will run, pop dialog AND THEN FINISH running!

to deal with this issue, we use a bit of a trick:

We add a true/false flag to our JS code AND WE WILL then click the button again!

So, I first just setup the button click (say to do the delete). I test, get that code working.

So, say this gridview:

            &lt;asp:GridView ID=&quot;GridView1&quot; runat=&quot;server&quot; AutoGenerateColumns=&quot;False&quot;
                CssClass=&quot;table table-hover&quot; Width=&quot;45%&quot;
                DataKeyNames=&quot;ID&quot; &gt;
                &lt;Columns&gt;
                    &lt;asp:BoundField DataField=&quot;FirstName&quot; HeaderText=&quot;First Name&quot;   /&gt;
                    &lt;asp:BoundField DataField=&quot;LastName&quot; HeaderText=&quot;First Name&quot;    /&gt;
                    &lt;asp:BoundField DataField=&quot;HotelName&quot; HeaderText=&quot;Hotel Name&quot;   /&gt;
                    &lt;asp:BoundField DataField=&quot;Description&quot; HeaderText=&quot;Descripiton&quot; /&gt;
                    &lt;asp:TemplateField HeaderText=&quot;Delete&quot; ItemStyle-HorizontalAlign=&quot;Center&quot;&gt;
                        &lt;ItemTemplate&gt;
                            &lt;asp:ImageButton ID=&quot;cmdDelete&quot; runat=&quot;server&quot;
                                ImageUrl=&quot;~/Content/trashcan1.png&quot;
                                Width=&quot;48px&quot;
                                Height=&quot;40px&quot; /&gt;
                        &lt;/ItemTemplate&gt;
                    &lt;/asp:TemplateField&gt;
                &lt;/Columns&gt;
            &lt;/asp:GridView&gt;

Now, in place of a plain button, I used a &quot;image button&quot;, but it still works 100% the same for this example.

So, now we need to write our server side delete code.

Keep in mind that a button on the page? Well, in most cases we can just double click on the button to add a click event.

However, for buttons inside of say a gridview, repeater, listview etc.?

Well, we can&#39;t do that &quot;simple&quot; click on control, since we get the gridview or whatever &quot;container&quot; has that control.

However, you STILL can add that plain click event, and the way we do that is to add the click event in markup.

you type in onclick=, and when you hit &quot;=&quot;, then inteli-sense pops up, and &quot;provides&quot; the option to add a click event. The result is thus 100% the same for the button (say if it was outside of the gridview).

So, that looks like this:

[![enter image description here][2]][2]

so, for listview, repeater, or any type of data bound control, you can STILL drop in that plain button (or in this example an image button).

And as above shows, that&#39;s how we add the click event (since we can&#39;t double click on such nested buttons inside of the gridview).

So now we write our delete a hotel row code. That code is thus this:

    Protected Sub cmdDelete_Click(sender As Object, e As ImageClickEventArgs)

        Dim btn As ImageButton = sender
        Dim gRow As GridViewRow = btn.NamingContainer

        &#39; get database row PK id
        Dim intPK As Integer = GridView1.DataKeys(gRow.RowIndex).Item(&quot;ID&quot;)

        Dim strSQL =
            $&quot;DELETE FROM tblHotelsA WHERE ID = {intPK}&quot;

        MyExecute(strSQL)
        LoadGrid()    &#39; re-load grid update display

    End Sub

Again note the nice trick/tip to get the current row. This works for listview, gridview, repeater etc.


Ok, so now we have a working delete button.

However, as I noted, buttons have both client side click and server side events.

And if that routine returns true, then server side button runs, and if the js code returns false, then the server side button does not run.

So, let&#39;s add our client side click to that button.

this code:

    &lt;asp:ImageButton ID=&quot;cmdDelete&quot; runat=&quot;server&quot;
        ImageUrl=&quot;~/Content/trashcan1.png&quot;
        Width=&quot;48px&quot;
        Height=&quot;40px&quot;
        onclick=&quot;cmdDelete_Click&quot;
        OnClientClick=&quot;return mydelpop(this,&#39;&lt;h4&gt;&lt;i&gt;Delete Hotel?&lt;/h4&gt;&lt;/i&gt;&#39;)&quot;
        /&gt;

We pass 2 values. &quot;this&quot; means the current button. I like passing that, since then we can use the position to place the dialog RIGHT beside the row button we clicked on on the gv. 

Since I like delete button on the right side of the gv, then I pop the top most right corner of the dialog to the lower left corner of the button we just clicked on.

And now our jQuery.UI dialog code.

    &lt;script&gt;
        var mydelok = false
        function mydelpop(btn,sPrompt) {

            if (mydelok) {
                mypopok = false
                return true
            }

            myDialog = $(&quot;#mypoparea&quot;)
            myDialog.html(sPrompt)
            myDialog.dialog({
                title: &quot;Delete Record&quot;,
                modal: true,
                sizable: true,
                width: &#39;380&#39;,
                closeText: &quot;&quot;,
                position: { my: &#39;right top&#39;, at: &#39;left bottom&#39;, of: btn },
                buttons: {
                    Delete: function () {
                        myDialog.dialog(&#39;close&#39;)
                        mydelok = true
                        btn.click()
                    },
                    cancel: function () {
                        myDialog.dialog(&#39;close&#39;)
                    }
                }
            })
            return false
        }
    &lt;/script&gt;

Note VERY close what the above does.

We set a var mydelok = false.

The user clicks on the button, calls our code, display dialog and RETURNS FALSE to the button!!!! As noted, such code does NOT halt like js alert() or confirm(). js code is &quot;asynchronous&quot;.

So, now the dialog is display.

If user hits cancel, then we just close dialog.

If user hits &quot;ok&quot; (delete), then we set our flag = true, AND THEN CLICK the button again!!! The button is clicked, client side code runs again, and this time it returns true, and thus server side code will run.

The end result looks like this:

Note how when I click on the delete button, the dialog box is position on the same row - this helps the user see which row they just clicked on.

[![enter image description here][3]][3]

So, I just tend to build, setup, write the code for the button in question.

I THEN add the jQuery.UI dialog to control if that button code will run or not.

As noted, a nice touch in a grid view is to add the &quot;position&quot; of the box to follow the were on the screen the button was clicked. This can be used for any button, but especially helps for a grid view example.

And as a FYI:
Since I so often have to do the above, I built a user control that I can just drop onto a form, and thus I don&#39;t have re-write this same code over and over each time I need a dialog confirm for code behind.

Edit: What about both changing the dialog and confirm/run server side button
=====

Ok, this could be a &quot;book&quot; sized response. And the short answer is you don&#39;t combine the two concpets!!!

So, our 2 concepts are:

Dialog pop, run the server side button, yes or no.

Dialog pop, changing the buttons and text.

So, for all practicual purposes? Yes, it would be nice to combine the above 2 concpets. However, I don&#39;t recommend you do this.

Why?

Well, top on the list is you need 2 round trips. (that means 2 post-backs). To make a VERY long story short? Your job as a developer, and this is ESPECIALLY the case for web forms? they are VERY prone to using and causing too many post-backs. Abuse this design considartation? Then what will occur over time is users, and people evaluating your site and work will state that your using the WRONG technology (web forms). They will tell you to dump that old stuff, and thus you risk all your work as being outdated, and too server side heavy wise.

Remember, all these new fancy frameworks like react.js, and SPA pages (single page applications) are attempting to REDUCE full page post-backs. In fact, these frameworks attempt to move AS MUCH AS POSSIBLE to the client side browser. 

And they are shooting for this goal since THEN when a user clicks on a button, or does something the web page responds near instant. (gives users a desktop like or phone app like experience - not some old clunky web site).

So, while it is &quot;possible&quot; to combine the above 2 concepts? No, I don&#39;t recommend you do.

In other words, if I want to &quot;confirm&quot; a button? Then YOU as the designer better figure out what the buttons etc. are supposed to look like and THEN code out accordingly.

Does this require &quot;more&quot; effort on your part? Yes, it does!!

However, as a developer, we still going to use a GAZILLION types of dialogs - they are without question one of the MOST common types of requirements here. And with lots of dialogs, then we as a developer need that &quot;flexibilty&quot; to add many dialog boxes, or at least &quot;some&quot;, and when we add them, we want custom text for buttons etc.

So, what I done is build a FEW general routines to deal with these &quot;use cases&quot;.

So, for a gridview, delete row button? Well, you don&#39;t need to change EVERY time the resulting dialog. However, one could argue that my delete Hotel row button may VERY well want to say include the Hotel Name in the dialog box. You CAN do this, but I would not.

However, we STILL want that flexibility to change text.

So, for example, delete a file on page like this:

[![enter image description here][4]][4]

So, in above, I had a &quot;confirm&quot; and run server side code if you hit ok.

But, EACH row was the same, so LITTLE motivation and advantage exists to set the dialog text server side.

So, I have a routine setup for this.

I just happen to use a custom user control. (so I can just drag that control onto the form). It was this for above:

[![enter image description here][5]][5]

So, in above I set the ok text, cancel text, the icon, and the button to run when you click ok.

but, I did NOT need to change the content each time, so while it was &quot;static&quot;, I was able to set the text, title and buttons.

However, what about the case in which context DOES change.

Such as this example:

[![enter image description here][6]][6]

So, in above I used my SAME dialog library.

but, once again, LITTLE advantage existed to set the ok/cancel button text, but, the content INSIDE the 2 dialogs most certainly had to change, had to be dynamic, and had to be set by code behind.

However, the &quot;div&quot; that I pop in each case? I was able to set the content on page load. once again, I don&#39;t click the button, set the text, and FIRE again, since that&#39;s too many round trips (and I don&#39;t want the page to suffer a post-back. In fact the code in this example DOES NOT like extra post backs. You either close the page, or accept or reject.

So, in the above 2 dialogs?

I have this:

[![enter image description here][7]][7]

So, I allow one to specify a &quot;div&quot; for the content, and that&#39;s loaded by code behind (on page load).

However, the rest of the dialog? Same as always, I set the button text, the button icon, the button to run when clicked on, and the title.

So, by good design choices, I VERY rare have the requirement to set the buttons and options with code behind. And the MASSIVE bonues points is then I don&#39;t suffer 2 routine trips.

I mean, if you are going to click on a button, and say pop a dialog to edit a reocrd? Sure, you will suffere a round trip. (button click, load up div to edit, inject js to pop dialog). That&#39;s ok. But, for JUST a confirm dialog, I don&#39;t want 2 round trips. And thus as a developer descision, I don&#39;t set the buttons text ON CLICK each time, since that&#39;s too expensive from a user &quot;responsive&quot; point of view, and in most cases my ONLY goal is to setup those buttons - setting them up in some markup (client side code) or setting them up in some server side code does NOT really help a whole lot, but the elimination of round trips, and INSTANT response? That&#39;s gold!!

So, you need/want to cobbile together probley about 2-3 routines. One ceratinly will let you set the buttons, but in MOST cases, setting the text of the buttons can be done in client side code, and server side code does not help much. I suppose in a &quot;few rare&quot; cases, being able to set the text of the buttons server side could be done, but the downsides outweight the up-sides.

As noted, I needed quite a few dialog boxes for all kinds of things, and thus sat down, and wrote out the features I wanted.

Icons for buttons, dynamic &quot;body&quot; in that div - but optional.

I also add a &quot;position&quot; option 1 - lower left, 2, lower right, and page center.

And I also settled on font-awesome for the icons, since bootstrap 4 and later dropped support for their icons. 

so, short answer:

I don&#39;t need to set the text of the buttons server side - since few cases exist, but for dialogs that show some info, then fine. However, for a &quot;confirm&quot; button run? Nope, I don&#39;t do that, since it would cost me 2 round trips, and thus I don&#39;t allow it as a &quot;personal&quot; design decision, since web forms already has a un-fair bad rap in regards to posting back too many pages. And I want a FANTASTIC user experience.

However, you CAN most certainly say on page load or whatever, &quot;setup&quot; the text of the buttons - since then any time the dialog pops, the button text etc. will show as you like. I just don&#39;t think a double round trip is warranted for such use cases.


  [1]: https://i.stack.imgur.com/WxJsC.gif
  [2]: https://i.stack.imgur.com/xoQJo.gif
  [3]: https://i.stack.imgur.com/LA4Uv.gif
  [4]: https://i.stack.imgur.com/wO30x.gif
  [5]: https://i.stack.imgur.com/fkOSv.png
  [6]: https://i.stack.imgur.com/zys3j.gif
  [7]: https://i.stack.imgur.com/jL2so.png

</details>



huangapple
  • 本文由 发表于 2023年5月11日 03:34:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76222019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定