开发者

ASP.NET MVC - DropDownList Validation Problem

I've got two DropDownLists in a form on a page that contain the same values (a list of languages). I want to ensure that the user doesn't select the same value in each of the drop downs.

I've tried using JavaScript to ensure the selected values aren't the same, it works fine but the form submits anyway.

What's the best way to accomplish this?

开发者_运维百科Here's the code from my View:

    <script type="text/javascript">

    function CheckLanguageDDL() 
    {
        var form = document.getElementById("form0");

        var sourceLangIndex = form.SourceLanguage.selectedIndex;
        var targetLangIndex = form.TargetLanguage.selectedIndex;
        var strSourceLanguage = form.SourceLanguage.options[sourceLangIndex].text;
        var strTargetLanguage = form.TargetLanguage.options[targetLangIndex].text;

        if (strSourceLanguage == strTargetLanguage) 
        {
            alert("Source Language and Target Language must be different!");
            return;

        }
    }

</script>

    <% Html.BeginForm("Index", "Translate", FormMethod.Post, new { enctype = "multipart/form-data" }); %>

    <fieldset>
    <legend>Request</legend>

    <br />
    <div class="editor-label">
        <%: Html.LabelFor(m => m.SourceLanguage) %>:
     </div>
    <div class="editor-field">
        <%: Html.DropDownList("SourceLanguage", (IEnumerable<SelectListItem>)ViewData["SourceLanguages"]) %>
        <%: Html.ValidationMessageFor(m => m.SourceLanguage) %>
    </div>

    <br />
    <div class="editor-label">
        <%: Html.LabelFor(m => m.TargetLanguage) %>:
     </div>
    <div class="editor-field">
        <%: Html.DropDownList("TargetLanguage", (IEnumerable<SelectListItem>)ViewData["TargetLanguages"]) %>
        <%: Html.ValidationMessageFor(m => m.TargetLanguage) %>
    </div>

    <input type="submit" value="Submit Request" onclick="CheckLanguageDDL();" />
    </p>
    </fieldset>

Thanks.


Make the function return a true/false value that the form submit use that return value

function CheckLanguageDDL() 
{
    var form = document.getElementById("form0");

    var sourceLangIndex = form.SourceLanguage.selectedIndex;
    var targetLangIndex = form.TargetLanguage.selectedIndex;
    var strSourceLanguage = form.SourceLanguage.options[sourceLangIndex].text;
    var strTargetLanguage = form.TargetLanguage.options[targetLangIndex].text;

    if (strSourceLanguage == strTargetLanguage) 
    {
        return false;
    }

    return true;
}

And on the button:

onclick="return CheckLanguageDDL();"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜