简体   繁体   中英

Asp.net core MVC and JQuery submit

I have this code(JQuery) in my View:

 $("form").submit(function (e) {
                e.preventDefault();
                var form = this;
                var link = '@Url.Action("Action", "Controller")';
                var args = {
                    MyFVal: MyFVal.val(),
                    MySVal: MySVal.val()
                };
                $.ajax({
                    type: "GET",
                    url: link,
                    data: args,
                    dataType: "json",
                    success: function (data) {
                        alert(data.acces);
                        if (data.acces) {
                            AllEnable();
                            form.submit();
                        }
                        else {
                            alert(data.erromessage);
                        }
                    },
                    error: function () {
                        alert("Error. Kontaktujte správce.");
                    }
                });
            });

When I gets submitted then I have this if in my save action.

if (Request.Form.ContainsKey("Insert"))
{
    // do code that is supposed to run
}
else if (Request.Form.ContainsKey("Edit"))
{
    // do another code
}

My problem is that because I submitted form by JQuery this if and elseif never gets executed.

Thanks for any help!

You might want to pass value for your requirements in Action condition. See operationType sample parameter

    var obj = {
        UniqueId: modelUniqueId.val(),
        Name: modelName.val(),
        operationType: $("[name=operationType]").val()
    };

    $.ajax({
        type: "POST",
        url: '/hrms/Class/Index',
        data: obj,
        success: function (result) {

            if (result.success == true) {
                createAndProcessPageAlert("success", result.message);
            }
            else {
                createAndProcessPageAlert("error", result.message);
            }

And in your Controller \ Action

    [HttpPost]
    public JsonResult Index(string operationType, ClassModel model)
    {
        var result = new HttpResponseModel<ClassModel>();
        var user = Request.GetUserProfile();

        if (operationType == "add")

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