简体   繁体   中英

Client-side validation against an object in ASP.Net-MVC3?

I have ah HTML5 form with an action defined as follows:

@using (Html.BeginForm("SearchAction", "ResultsController"))

The form takes in two text fields:

<input type="text" name="txtSearchTerm" id="txtSearchTerm" class="frontPageInput" placeholder="Begin your search..." required />          
<input type="text" name="txtGeoLocation" id="txtGeoLocation"  class="frontPageInput" required />          

The txtGeoLocation field is an autocomplete field that is fed from a cached object, fed through the controller and by a model repository class through the following jQuery code:

<script type="text/javascript" language="javascript">
    $(function () {
        $("#txtGeoLocation").autocomplete(txtGeoLocation, {
            source: function (request, response) {
                $.ajax({
                    url: "/home/FindLocations", type: "POST",
                    dataType: "json",
                    selectFirst: true,
                    autoFill: true,
                    mustMatch: true,
                    data: { searchText: request.term, maxResults: 10 },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.GeoDisplay, value: item.GeoDisplay, id: item.GeoID }
                        }))
                    }
                })
            },
            select: function (event, ui) {
                alert(ui.item ? ("You picked '" + ui.item.label + "' with an ID of " + ui.item.id)
                    : "Nothing selected, input was " + this.value);
                document.getElementById("hidLocation").value = ui.item.id;
            }
        });

    });

There's an alert there for debugging. When clicking on the text that drops down, this alert fires, however it does not fire if you type in the whole word and hit submit.

I would like to first, validate the text in the geo text box on the client side, to ensure that it is a value contained in the collection, of not, have the text box in red, communicate that.

Thanks.

You can use jquery remote validation using the [Remote()] attribute to validate the value is in the list. You will have to do the same check on the server side when you post back as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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