asp.net-mvc 如何在 ASP.NET MVC 中使用 Web API 2 将数据插入数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24159571/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:43:52  来源:igfitidea点击:

How to insert data into database using Web API 2 in ASP.NET MVC

asp.net-mvc

提问by Sheo Narayan

I have below code in Controller

我在控制器中有以下代码

    // POST api/PersonalDetails
    [ResponseType(typeof(PersonalDetails))]
    [HttpPost]
    public IHttpActionResult PostPersonalDetails(PersonalDetails personaldetails)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        db.PersonalDetails.Add(personaldetails);
        db.SaveChanges();

        return CreatedAtRoute("DefaultApi", new { id = personaldetails.AutoId }, personaldetails);
    }

and below code in view

和下面的代码

<script type="text/javascript">
$("#btnAdd").click(function () {
    var PersonalDetails = {
        "FirstName": $("#FirstName").val(),
        "LastName": $("#LastName").val(),
        "Age": $("#Age").val(),
        "Active": $("#Active").val()
    };

    $.ajax({
        type: "POST",
        url: 'http://localhost:28206/api/PersonalDetails/PostPersonalDetails',
        data: JSON.stringify(PersonalDetails),
        dataType: "json",
        processData: true,
        success: function (data, status, xhr) {
            alert(status);
        },
        error: function (xhr) {
            alert(xhr.responseText);
        }
    });
});
</script>

Now, when I am clicking on the button that fires up btnAdd click method. The controller PostPersonalDetails method is executing but personaldetails object is null. I am not able to retrieve values of the form.

现在,当我单击启动 btnAdd 单击方法的按钮时。控制器 PostPersonalDetails 方法正在执行,但personaldetails 对象为空。我无法检索表单的值。

How to get values of the PersonalDetails object formed in the click event.

如何获取单击事件中形成的 PersonalDetails 对象的值。

回答by Sheo Narayan

Okay, I solved this problem and have written an article to help others.

好的,我解决了这个问题并写了一篇文章来帮助别人。

Inserting record into database using ASP.NET MVC with Web API

使用带有 Web API 的 ASP.NET MVC 将记录插入数据库

Hope this will be helpful for others looking for similar kind of problem.

希望这对寻找类似问题的其他人有所帮助。

Thanks

谢谢