【问题标题】:Validate a form using Web Api controller使用 Web Api 控制器验证表单
【发布时间】:2015-09-06 15:30:41
【问题描述】:

我有一个 web api 应用程序,其中有这个表单:

     <form id="editForm">

                    <input id="editid" type="hidden" name="id" />
                    <p><label>Numéro cnss </label><input id="cnss" name="cnss" /><label style="color:red" id="labError"> ( * )</label></p>
                    <p><label>Nom </label><input id="lastname" name="lastname" /><label style="color:red" id="labError"> ( * )</label></p>
                    <p><label>Prénom </label><input id="firstname" name="firstname" /><label style="color:red" id="labError"> ( * )</label></p>
                    <p><label>Adresse   </label> @Html.TextArea("address", new { id = "address" })<label style="color:red" id="labError"> ( * )</label></p>

                    <p><label>Lieu de naissance </label><input id="birth_place" name="birth_place" /> </p>
                    <p><label>Mutuelle </label><input id="mutuelle" name="mutuelle" /><label style="color:red" id="labError"> ( * )</label></p>
                    <p><label>Caisse d'assurance maladie </label><input id="caisse_assu_maladie" name="caisse_assu_maladie" /><label style="color:red" id="labError"> ( * )</label></p>

                    <p>
                        <label>Type de client   </label>
                        <select id="client_type" name="client_type">
                            <option value="demande de transport régulière sur une période">demande de transport régulière sur une période</option>
                            <option value="demande de transport régulière et indéfinie">demande de transport régulière et indéfinie</option>
                            <option value="Ponctuel ">Ponctuel </option>
                        </select>
                    </p>

                </form>
 <button id="btnStepTwo" type="submit" class="btn btn-primary" >Commencer la réservation</button>

在 Api 控制器中,我有这个动作:

 [HttpPost]
        public bool ValidateClient(ClientModel item)
        {
            return ModelState.IsValid;  
        }

我想为表单中的每个更改添加一个javascript方法,该方法调用ValidateClient服务来验证表单中的模型是否有效:如果模型有效==>按钮将被启用,否则将被禁用。

  1. 我怎样才能完成这项任务?
  2. 最好和最简单的方法是什么?

【问题讨论】:

标签: javascript c# jquery ajax asp.net-mvc


【解决方案1】:

您将change() 事件附加到输入:

$('input').on('change', function (e) {
    var el = $(e.currentTarget);
    $.post(url, $('form').serialize(), function (data) {
        if (data) {
            // do stuff to "el"
        }
    });
});

从 REST 的角度来看,您可能希望使用正确的 HTTP 代码进行响应。如果模型无效,则不确定 200 响应是否有意义。

【讨论】:

    猜你喜欢
    • 2015-04-25
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多