在发送到控制器之前,使用javascript从方法中的文本框中解析所有值

时间:2013-05-02 14:48:19

标签: javascript asp.net-mvc string textbox

我在这里有这个静态方法:

public static string ParseStringForSpecialChars(string stringToParse)
{
    const string regexItem = "[^a-zA-Z0-9 ]";

    string stringToReturn = Regex.Replace(stringToParse, regexItem, @"\$%&'");

    return stringToReturn;
}

此方法可以正常工作,因为它可以阻止许多字符串对我的应用程序造成危害。我想有更好的办法,但这不是我的职位。

现在我想要的是从javascript中获取任何文本框中的所有值,这些文本框将调用此方法,然后将数据发送到控制器。

说我有这个观点:

@using MyApp.Utilities
@model List<MyApp.Models.CustomerObj>

@{
    ViewBag.Title = "Customer Index";
}

<h2>Customer Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
    @using (Html.BeginForm())
    {
        <p>
            Name: @Html.TextBox("customerName") <br/>
            Address: @Html.TextBox("customerAddress") City: @Html.TextBox("customerCity") <br/>
             <br />
            Postal Code: @Html.TextBox("customerPC")<br/>
            Phone Number: @Html.TextBox("customerPhone") Fax Number: @Html.TextBox("customerFax")<br />
            Mail: @Html.TextBox("customerEmail")  <br/>
            <input type="submit" value="Filter" style="float:right">
        </p>
    }
</p>

我怎么能继续做我想做的事?任何人都可以向我提出建议如何进行?我想要一个灵活的解决方法,因为你现在的观点将会改变,我需要这种方法在任何地方都适用。

谢谢。

1 个答案:

答案 0 :(得分:1)

您是否考虑过将数据注释添加到模型中,如下所示:

[RegularExpression(@"^\$?\d+(\.(\d{2}))?$")]

这是从http://www.asp.net/mvc/tutorials/older-versions/models-%28data%29/validation-with-the-data-annotation-validators-cs

中捕获的

当然,这样做的缺点是您必须将它添加到模型中要应用的所有属性中。您可以使用远程验证并通过javascript将其关闭。否则,您将无法在客户端执行此操作。 (但这并不难做到。)

相关问题