简体   繁体   English

将C#转换为客户端Javascript

[英]Convert C# to clientside Javascript

I have an Asp.Net page with a list of options accompanied by a checkbox in a ListView control. 我有一个Asp.Net页面,其中包含选项列表以及ListView控件中的复选框。 I have applied Paging using the paging control. 我已使用分页控件应用了Paging。 However I want to maintain the status of the checkboxes across the various paged pages of the ListView. 但是,我想在ListView的各个页面上维护复选框的状态。 I have done this with the following code 我用以下代码完成了此操作

private List<int> IDs
    {
        get
        {
            if (this.ViewState["IDs"] == null)
            {
                this.ViewState["IDs"] = new List<int>();
            }
            return (List<int>)this.ViewState["IDs"];
        }
    }

protected void AddRowstoIDList()
{
    int checkAction = 0;

    foreach (ListViewDataItem lvi in lvCharOrgs.Items)
    {
        CheckBox chkSelect = (CheckBox)lvi.FindControl("chkSelect");
        if ((((chkSelect) != null)))
        {
            int ID = Convert.ToInt32(lvCharOrgs.DataKeys[lvi.DisplayIndex].Value);


            if ((chkSelect.Checked && !this.IDs.Contains(ID)))
            {
                this.IDs.Add(ID);
                checkAction += 1;
            }
            else if ((!chkSelect.Checked && this.IDs.Contains(ID)))
            {
                this.IDs.Remove(ID);
            }
        }
    }
}

protected void lvCharOrgs_ItemDataBound(object sender, ListViewItemEventArgs e)
{
    ListViewDataItem lvi = (ListViewDataItem)e.Item;
    if ((lvi.ItemType == ListViewItemType.DataItem))
    {
        // Find the checkbox in the current row
        CheckBox chkSelect = (CheckBox)lvi.FindControl("chkSelect");
        // Make sure we're referencing the correct control
        if ((chkSelect) != null)
        {
            // If the ID exists in our list then check the checkbox
            int ID = Convert.ToInt32(lvCharOrgs.DataKeys[lvi.DisplayIndex].Value);
            chkSelect.Checked = this.IDs.Contains(ID);
        }
    }

    if (Profile.proUserType == "basic")
    {//basic account so no choice of charity
        ((CheckBox)e.Item.FindControl("chkSelect")).Checked = true;
        ((CheckBox)e.Item.FindControl("chkSelect")).Enabled = false;
    }
}

Now I have a CustomValidator control which checks to ensure between 3 & 5 records have been selected. 现在,我有一个CustomValidator控件,该控件进行检查以确保已选择3至5条记录。 If this is true the page is valid and processed. 如果是这样,则该页面有效并已处理。 If it is not the case (eg less than 3 or more than 5) the page is Invalid and the CustomValidator throws up a label to notify of this fact. 如果不是这种情况(例如小于3或大于5),则该页面无效,并且CustomValidator抛出标签以通知这一事实。

I use the following code on the serverside to implement this. 我在服务器端使用以下代码来实现此目的。

protected void lvCharOrgsValidator_ServerValidate(object source, ServerValidateEventArgs args)
{// Custom validate lvCharOrgs
   //update selected rows
    AddRowstoIDList();
    //get count and verify is correct range
    int counter = this.IDs.Count;
    args.IsValid = (counter >=3 && counter <=5) ? true : false;
}

This all works fine except I need to implement a 'ValidatorCallout' extender from the AJAX Control Toolkit. 除了我需要从AJAX Control Toolkit实现“ ValidatorCallout”扩展器之外,所有这些都工作正常。 However this doesn't work with CustomValidators unless they implement clientSide validation. 但是,除非CustomValidator实现了clientSide验证,否则这不适用于CustomValidator。 Thus I need to convert the 'lvCharOrgsValidator_ServerValidate' method to a clientside JavaScript function. 因此,我需要将“ lvCharOrgsValidator_ServerValidate”方法转换为客户端JavaScript函数。

Hope this clarifies my requirements. 希望这可以澄清我的要求。

What does the following do? 以下是做什么的?

AddRowstoIDList();

Something like the following is a start, but will need more details on the above method to provide a working answer 像下面这样的东西是一个开始,但需要上述方法的更多细节才能提供有效的答案

function validateRowCount(sender, args) {
    //update selected rows
    AddRowstoIDList(); // Does this add row indexes to an array?

    //get count and verify is correct range
    var counter = IDList.length;
    args.IsValid = (counter >=3 && counter <=5);
}

It might be worth looking at Script# for a longer term solution, if you're planning on doing a lot of conversion. 如果您打算进行大量转换,则可能值得考虑使用Script#作为长期解决方案。

EDIT: 编辑:

now I can see the AddRowstoIDList() method, to do this on the client-side will be slightly different. 现在,我可以看到AddRowstoIDList()方法,在客户端执行此操作将略有不同。 Firstly, get a reference to the DOM element that is rendered for lvCharOrgs . 首先,获取对为lvCharOrgs呈现的DOM元素的引用。 Probably the most straightforward way to do this in vanilla JavaScript would be to put the JavaScript function in the page and use the server tags to get the rendered ClientID. 在原始JavaScript中执行此操作的最直接方法可能是将JavaScript函数放入页面中,并使用服务器标签获取呈现的ClientID。

function validateRowCount(sender, args) {
    var lvCharOrgs = document.getElementById('<%= lvCharOrgs.ClientID %>');

    var checkboxes = lvCharOrgs.getElementsByTagName('input');
    var len = checkboxes.length;
    var counter = 0;

    for(var i =0; i < len; i++) {
        if (checkboxes[i].type == "checkbox" && checkboxes[i].checked) counter++;
    }
    args.IsValid = (counter >=3 && counter <=5);
}

Should work something like this - Working Demo 应该像这样工作 - 工作演示

add /edit to the URL if you want to see the code 如果要查看代码,请在URL中添加/ edit

Have a look at this article. 看看这篇文章。 It applies to asp.net mvc, but it also covers some basics and you might be able to do something similar for asp.net. 它适用于asp.net mvc,但它也涵盖了一些基础知识,您也许可以对asp.net做类似的事情。 In particular, you might find the jquery remote validation attributes shown in the article useful for what you intend to do. 特别是,您可能会发现本文中显示的jquery远程验证属性对您打算执行的操作很有用。

If you change int to var , your code is valid JavaScript. 如果将int更改为var ,则您的代码是有效的JavaScript。 (But since it depends on other functions and objects you need to convert those as well.) Also if you're using the c# 3.5 compiler it will stay valid C# even with var instead of int. (但是,由于它取决于其他函数和对象,因此也需要转换它们。)另外,如果您使用的是c#3.5编译器,即使使用var而不是int,它也将保持有效的C#。

Probably not what you want, but there is jsc : 可能不是您想要的,但是有jsc

"Web 2.0 hype? Want build better web sites, but javascript is too hard? No real IDE? Maybe you should try jsc. The web app can be built within Visual Studio 2008 or any other c# compliant IDE, and then the application magically appears. You should think of it as a smart client. Precompile your c# to javascript with jsc! As an option instead of using IIS and asp.net, you could get away by using apache, with mysql and php." “ Web 2.0炒作?想要构建更好的网站,但是javascript太难了?没有真正的IDE?也许您应该尝试使用jsc。可以在Visual Studio 2008或任何其他与c#兼容的IDE中构建该Web应用程序,然后该应用程序神奇地出现您应该将其视为智能客户端。使用jsc将c#预编译为javascript!作为一种选择,而不是使用IIS和asp.net,可以通过使用apache,mysql和php来摆脱困境。”

SharpKit converts C# to client side javascript. SharpKit将C#转换为客户端javascript。

https://sharpkit.github.io/ https://sharpkit.github.io/

Well, you can always include your own javascript with custom validators. 好吧,您始终可以在自定义验证器中包含自己的JavaScript。 Here is a link to an article that introduces adding javascript to a validator. 这里是文章的链接,该文章介绍了将JavaScript添加到验证器。 You just have to write your own javascript, really. 实际上,您只需要编写自己的JavaScript。

我听说过从c#(或者是IL?)到JavaScript的交叉编译器,但不幸的是不再记得该名称了,但是google搜索出现了这样的东西: http : //jsc.sourceforge.net/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM