ASP.NET Several ways for MVC to submit forms (verification + submission + background receiving)

Native submission method

That is, add the action attribute to the form tag

verification

  • Verify to add the required attribute (h5) to the input tag directly. This attribute must be used with the button of type="submit". If the button type is not submit, then this required attribute has no meaning.
  • Verify that other (when using regular expressions or length restrictions) use the onsubmit attribute. Onsubmit returns false to not submit the form, and returns true to submit the form.

There are two ways to verify a native submission

Under the form tab, add onsubmit="return functionName()

   <form id="teamForm" action="getTeam" onsubmit="return demo()">
        <div class="form-group row">
            <label class="col-md-2" for="customer"></label>
            <div class="col-md-10">
                <input name="customer" type="text" class="form-control" id="customer" placeholder="Please enter customer name" required>
            </div>
          
        </div>
        <div class="form-group row">
            <label class="col-md-2" for="description">Product description</label>
            <div class="col-md-10">
                <input name="description" type="text" class="form-control" id="description" placeholder="Please enter product description" required>
            </div>
        </div>
        <button type="submit" class="btn btn-primary">Billing</button>
    </form>
    <script>
        function demo() {
        //Write verification
    }
    </script>

Bind submit event for form in js

    $("#teamForm").bind("submit", function () {
        //Write verification
    })

Reminders after validation failure

Because alert is used in many cases, but its user experience is not very good. It needs to be clicked every time, so it is not recommended to use it
The required property of h5 (indicating required item), which will disappear automatically after a few seconds of verification, is applicable to the following types: text, search, url, telephone, email, password, date pickers, number, checkbox, radio and file. The required mentioned above can only be used with the button of type='submit '


If you want to modify the default prompt, add oninvalid="setCustomValidity('Please fill in the customer name ');" oninput="setCustomValidity(')" to the input

   <input name="customer" type="text" class="form-control" id="customer" placeholder="Please enter customer name" required oninvalid="setCustomValidity('Please fill in the customer name');" oninput="setCustomValidity('');">

Limit the number of input characters (with bootstrap dependency)

oninput is a real-time monitoring of user input. Its use can greatly improve efficiency.

    $(function () {
        checkLen("#customer", 10);//Limit input to 10 characters
        checkLen("#description", 10);//10 characters
    })
    function checkLen(element, length) {
        $(element).on("input propertychange", function (event) {
            var len = $.trim($(element).val()).length;
            if (len > length) {
                $(element).val($.trim($(element).val()).substring(0, length));
                showPopover($(element), "Limited input" + length + "A word");
                return;
            }
        })
    }
    function showPopover(target, msg) {
        target.attr("data-original-title", msg);
        $('[data-toggle="tooltip"]').tooltip();
        target.tooltip('show');
        target.focus();
        //The prompt box disappears in 2 seconds
        var id = setTimeout(
          function () {
              target.attr("data-original-title", "");
              target.tooltip('hide');
          }, 2000
        );
    }

Regular expression limit can only enter numbers

value = value.replace(/[^\d]/g, '');

It indicates that the regular expression in the bracket does not match is replaced with a space, g indicates global search, and all characters in value that are not numbers are replaced with spaces.

Add after the oninput event above

    var reg = /^\d$/g;
    if (!reg.test($.trim($(element).val()))) {
        var value = $.trim($(element).val());
        value = value.replace(/[^\d]/g, '');
        $(element).val(value);
        showPopover($(element), "Only numbers can be entered");
    }

Background access

Depends on method
get is submitted. The url parameter is composed of name as the key value pair, which is spliced in the url( http://www.example.com/example/program?x=28&y=66
)Later, use when getting Request.QueryString["name"]
Post is used to submit forms. Because get is not secure, most of the time post is used.
Background receiving and using Request.Form["name"]
Do not forget the HttpPost header when submitting in post mode, which means it is a post request

  [HttpPost]
        public ActionResult getTeam()
        {
            var customer = Request.Form["customer"];
            var pwd = Request.Form["description"];
      }

ajaxSubmit submit

You need to download the form plug-in of jquery. The treasure address is pasted below
Plug in download address

            $("#teamForm").ajaxSubmit({
                url: "Home/getTeam",
                type: "post",
                dataType: "json",
                data:{"id":"3"},//Define parameter acquisition in getTeam method
                beforeSubmit: function () {//If false is returned, the form will not submit data that can be used for form validation and processing before submission
                    console.log("before");
                },
                success: function (responseText, statusText, xhr, $form) {
                    console.log(eval(responseText));
                    if (eval(responseText)) {
                        alert("Billing success");
                    } else {
                        alert("Billing failure");
                    }
                },
                error: function (xhr, status, err) {
                    alert("error");
                },
            clearForm: true,    // After a successful submission, clear the form
            resetForm: true    // After a successful submission, reset the form fill in
            })
        [HttpPost]
        public JsonResult getTeam(string id)
        {
            var customer = Request.Form["customer"];
            var pwd = Request.Form["description"];
            var paraid = id;
            return Json(true);
        }

So it seems that ajaxSubmit is more convenient than native submission, after all, there is callback processing.
If there is any mistake, please correct it.
There are also upload files for the form content, which will be listed in the next section.

Keywords: Attribute JSON JQuery

Added by DoctorWho on Tue, 16 Jun 2020 09:08:51 +0300