jQuery在其他代码之后运行C#代码

时间:2015-05-15 12:17:02

标签: c# jquery

我在按钮上有一个点击事件,它运行一些C#中的代码,所以我使用@{...}将我的C#代码放在jQuery中,但@{...}中的代码运行在其他代码之后。

HTML代码:

   <button type="submit" id="TestRegex" class="btn btn-default">Test Regex</button>

jQuery的:

 $("#TestRegex").click(function () {
            @{
                var testdata = Request["TestData"];
                var expression = Request["RegexPattern"];
                string regexMatchResult = "No Match";
                string dateMatchResult = "No Match";

                if (!string.IsNullOrEmpty(testdata) || !string.IsNullOrEmpty(expression))
                {
                    bool regexMatch =
                        System.Text.RegularExpressions.Regex.IsMatch(testdata, expression, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    bool dateMatch = false;

                    foreach (var item in System.Text.RegularExpressions.Regex.Matches(testdata, expression))
                    {
                        dateMatch = string.Compare(item.ToString(), testdata, true) == 0;
                    }

                    regexMatchResult = regexMatch ? "RegEx Match" : "No Match";
                    dateMatchResult = dateMatch ? "Date Matches" : "No Match";
                }
              }

            $('#RegExMatch').text("@regexMatchResult");    //
            $('#DateMatchResult').text("@dateMatchResult"); // These codes are run before codes above

        });

1 个答案:

答案 0 :(得分:0)

此部分应位于顶部

@{
                var testdata = Request["TestData"];
                var expression = Request["RegexPattern"];
                string regexMatchResult = "No Match";
                string dateMatchResult = "No Match";

                if (!string.IsNullOrEmpty(testdata) || !string.IsNullOrEmpty(expression))
                {
                    bool regexMatch =
                        System.Text.RegularExpressions.Regex.IsMatch(testdata, expression, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                    bool dateMatch = false;

                    foreach (var item in System.Text.RegularExpressions.Regex.Matches(testdata, expression))
                    {
                        dateMatch = string.Compare(item.ToString(), testdata, true) == 0;
                    }

                    regexMatchResult = regexMatch ? "RegEx Match" : "No Match";
                    dateMatchResult = dateMatch ? "Date Matches" : "No Match";
                }
              }

然后在Script标签

 $(document).ready(function(){
     $('#RegExMatch').text("@regexMatchResult");    //
     $('#DateMatchResult').text("@dateMatchResult");


     $("#TestData").text("@testdata "); 
     $("#RegexPattern").text("@expression "); 
 });