Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
104 views
in Technique[技术] by (71.8m points)

c# - Passing value from MVC View to Controller using ajax

I am developing web app with asp.net core 3.1. I have an ajax call sends a ConsultViewModel object to my controller, but in controller it is getting null. I don't understand my error. I changed the ajax "data: JSON.stringify({consultView: consultView})" to "data: JSON.stringify(consultView)" but error persist. How do i solve this problem?

My code is just as follow:

ViewModel

public class ConsultViewModel
{
    public int Id { get; set; }
    [Range(1, int.MaxValue, ErrorMessage = "Select a Department")]
    public int DepartmentId { get; set; }
    [Required]
    public string Description { get; set; }
    public string Date { get; set; }
    public IEnumerable<SelectListItem> Department { get; set; }
}

View

@model MyApp.AppWeb.Models.ConsultViewModel;

    <h1>Edit</h1>
    <form asp-action="Edit">
        <div asp-validation-summary="ModelOnly" class="text-danger"></div>
        <input type="hidden" asp-for="Id" />

        <div class="form-group">
            <label asp-for="DepartmentId" class="control-label"></label>
            <select asp-for="DepartmentId" asp-items="Model.Department" class="form-control"></select>
            <span asp-validation-for="DepartmentId" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="Dateate" class="control-label"></label>
            <input asp-for="Date" class="form-control" disabled />
            <span asp-validation-for="Date" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="Description" class="control-label"></label>
            <textarea asp-for="Description" class="form-control" cols="40" rows="5"></textarea>
            <span asp-validation-for="Description" class="text-danger"></span>
        </div>

        <div id="@Model.Id" class="form-group">
            <input type="button" class="btn btn-primary" value="Save" id="btnEdit"/>
        </div>
    </form>

Scripts

@section Scripts {
@{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

<script type="text/javascript">
    $(document).ready(function () {
        $('#btnEdit').click(function () {
            var id = $(this).parent()[0].id;
            var consultView = {
                Id: id,
                DepartmentId: $('#DepartmentId').val(),
                Date: $('#Date').val(),
                Description: $('#Description').val()
            };

            $.ajax({
                type: 'POST',
                url: "@Url.Action("Editar")",
                contentType: "application/json; charset=utf-8",
                dataType: 'json',
                data: JSON.stringify({consultView: consultView}), 
                success: function (data) {
                    alert(data.message);
                },
                error: function (ex) {
                    alert('Error.' + ex);
                }
            });
        });
    });
</script>

}

[HttpPost]
    //[ValidateAntiForgeryToken]
    public async Task<IActionResult> Edit(ConsultViewModel consultView)
    {
        if (ModelState.IsValid)
        {
            //More code..

            return Json(new { success = true, message = "Done." });               
        }

        return View(consultaView);
    }

Thank!

question from:https://stackoverflow.com/questions/65947841/passing-value-from-mvc-view-to-controller-using-ajax

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have an ajax call sends a ConsultViewModel object to my controller, but in controller it is getting null.

You can try to modify the code to stringify your JavaScript object consultView directly, need not to construct a new JavaScript object {consultView: consultView}.

data: JSON.stringify(consultView),

Besides, apply [FromBody] attribute to parameter like below.

public async Task<IActionResult> Edit([FromBody]ConsultViewModel consultView)
{

Testing data that I sent

enter image description here

Posted data can be bound as expected

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...