Метод действия Call Post из запроса jquery ajax

Как я могу вызвать метод действия из формы jquery ajax? Я создаю код ниже, но параметры в моем методе действия всегда равны нулю. Примечание. Я уже добавил все необходимые скрипты, такие как quill.js, jquery.unobtrusive-ajax.js. У меня есть такая форма:

<form data-ajax="true" data-ajax-method="post" method="post">
    <input type="text" name="postTitle" class="form-group" />

    <div id="postData" name="postData"></div>

    <br />
    <button type="submit" class="btn btn btn-outline-dark" id="btnCreate">Create post</button>
</form>

и этот скрипт javascript и jquery: QUILL:

<script>
        var toolbarOptions = [
            ['bold', 'italic', 'underline', 'strike'],         // toggled buttons
            ['blockquote', 'code-block'],

            [{ 'header': 1 }, { 'header': 2 }],                // custom button values
            [{ 'list': 'ordered' }, { 'list': 'bullet' }],
            [{ 'script': 'sub' }, { 'script': 'super' }],      // superscript/subscript
            [{ 'indent': '-1' }, { 'indent': '+1' }],          // outdent/indent
            [{ 'direction': 'rtl' }],                          // text direction
            [{ 'size': ['small', false, 'large', 'huge'] }],   // custom dropdown
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
            ['link', 'image', 'video', 'formula'],             // add's image support
            [{ 'color': [] }, { 'background': [] }],           // dropdown with defaults from theme
            [{ 'font': [] }],
            [{ 'align': [] }],
            ['clean']                                          // remove formatting button
        ];

        var quill = new Quill('#postData', {
            modules: {
                toolbar: toolbarOptions
            },
            theme: 'snow'
        });
    </script>

Вызов метода почтового действия:

$(function () {
            $('#btnCreate').click(function () {
                var props = [{
                    "PostTitle": $("postTitle"),
                    "PostData": quill.root.innerHTML
                }]

                $.ajax({
                    url: '@Url.Action("Create", "Post")',
                    type: "POST",
                    data: { JSON.stringify(props) },
                    contentType: "application/json",
                    dataType: "json",
                    async: true,
                    success: successFunc,
                    error: errorFunc 
                });

                function successFunc(data, status) {
                    alert(data);
                }

                function errorFunc(e) {
                    console.log('Error!', e);
                }
                //console.log(postData);
            });
        });

Мой метод действий:

[HttpPost]
        [ActionName("Create")]
        public async Task<IActionResult> CreatePost(string props) // here props is null
        {
            Post post = new Post { PostBody = props };
            db.Posts.Add(post);
            await db.SaveChangesAsync();

            return View();
        }

person Farid Huseynli    schedule 22.04.2020    source источник
comment
вы используете .netCore? параметр действия должен быть коллекцией объектов, которые должны иметь два свойства PostTitle и PostData   -  person Mohammed Sajid    schedule 23.04.2020
comment
Да, я использую ядро ​​.net. Спасибо, я проверю вашу рекомендацию.   -  person Farid Huseynli    schedule 23.04.2020
comment
добро пожаловать!, не забудьте [FromBody] за мое предложение.   -  person Mohammed Sajid    schedule 23.04.2020


Ответы (1)


Я думаю, что каждый элемент ввода получается из val();

 $("postTitle").val() maybe
person AgungPanduan.Com    schedule 23.04.2020