0

を呼び出すAJAXを作りましたIActionResult。しかし、モデルを渡すことはできません。文字列を渡すだけです。私の質問は、代わりにモデルを渡す方法ですか?

AJAX

    $('#CreateLesson').on('submit', function (e) {
        e.preventDefault();
        
        var lesson = $(this).serialize();

        $.ajax({
        type: "POST",
        url: '@Url.Action("Create", "Lessons")',
        dataType: "json",
        async: false,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(lesson),
        success: function (data) { alert("succes"); },
        error: function (error) {
            console.log(error);
            alert(JSON.stringify(error));
        }
        });
    });

コントローラ

    [HttpPost]
    //[ValidateAntiForgeryToken]
    public IActionResult Create([FromBody]string lesson)
    {
        if (ModelState.IsValid)
        {
            _context.Add(lesson);
            _context.SaveChanges();
            return PartialView("_MyLessons", lesson);
        }
        return RedirectToAction("AjaxMetho", "Account");
        //return PartialView("Create");
    }

テキストが出てくるのは変です。モデルよりも多くのフィールドがあります。私のモデルには、名前、グレード、目的、説明しかありません。

"Name=C%23%20vvvvvv&grade=1&SubID=123&BarCode=vvvvvvnnnnnnnnnnnnnn&Objectives=ABC%40abc123&Description=ABC%40abc123&__RequestVerificationToken=CfDJ8Ekvaq-NSQtAn7SGG0DJv7-ETDuOvAlwPoMzNMGyUSfJ6RRc2UY3KRxQbq0VEzBRE-YgHTSeMtnKY8DqTKXk8GoGsvkcB87xEM0-G5zbBO6BtoWLncH1ROE7iE2kiUbjBsPg_pwzZpXPUhS9_Nb14ay02l-N_DSULUT22cTa8zY5zpcyHY5Nsp-mN7tfLYiOGA"

文字列化せずにモデルを渡そうとしIActionResult、文字列の代わりにレッスンモデルを取得するようにパラメーターを変更すると、null が返されます!!

モデルを問題なく渡すにはどうすればよいですか?

4

2 に答える 2

0

Ajax 経由でフォームのデータを送信し、バックグラウンドでモデルを受け取りたいようです。簡単な例を次に示します (formData でデータを渡したので、コントローラーは [FromBody] を必要としません)。

意見:

 <form method="post" id="CreateLesson" enctype="multipart/form-data">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <h4>Name</h4>
        <input type="text" class="form-control" name="name" value="" />
        <h4>Grade</h4>
        <input type="text" class="form-control" name="grade" value="" />
        <h4>Objectives</h4>
        <input type="text" class="form-control" name="objectives" value="" />
        <h4>Description</h4>
        <input type="text" class="form-control" name="description" value="" />
        <input type="submit" value="Create" class="btn btn-primary" />
    </form>

あなたの見解のJS:

@section Scripts{
<script>
    $('#CreateLesson').submit(function (e) {
    e.preventDefault();

        var formData = new FormData($('#CreateLesson')[0]);
 
    $.ajax({
            type: "POST",
            url: "/Lessons/Create",
            async: true,
            data: formData,
            cache: false,
            processData: false,
            contentType: false,
            success: function (data) {
                console.log("Ok")
            },
            error: function (data) {
            }
        });
</script>}

あなたのコントローラー:

public IActionResult Create()
    {
        return View();
    }

    [HttpPost]
    //[ValidateAntiForgeryToken]
    public IActionResult Create(Lesson lesson)
    {
       
        return RedirectToAction("AjaxMetho", "Account");
      
    }

結果:

ここに画像の説明を入力

于 2020-08-25T02:14:40.413 に答える
0

もっと簡単な解決策を見つけました

// View
//<form id="CreateLesson" asp-action="Create" asp-controller="Lessons" method="post" enctype="multipart/form-data">

// Ajax
$('#CreateLesson').on('submit', function (e) {

    e.preventDefault();
    var lesson = $(this).serialize();
    var Url = $(this).attr('action');
    $.post(Url, lesson);

});

// Controller
//public JsonResult Create(Lesson lesson) { }
于 2020-08-25T21:05:22.950 に答える