【问题标题】:How to pass data to database in ASP.NET MVC?如何在 ASP.NET MVC 中将数据传递到数据库?
【发布时间】:2021-05-04 10:45:32
【问题描述】:

我正在开发一个 MVC 项目。我的要求是通过表单将数据插入数据库。我已将表单包含在引导模式中。

我的问题是,当我输入一些数据并单击保存按钮时,它只插入空行,而不是输入的值。为什么会这样?如何使其插入实际值而不是仅传递空值?

这是模式的代码。

@if (Model != null)
{
    <div class="modal-content">

        <!--modal header-->

        <div class="modal-body">
            <form id="actionForm">
                <div class="form-group">
                    <label>Name</label>
                    <input type="text" name="Name" class="form-control" placeholder="Enter Accomodation Type Name...">
                </div>
                <div class="form-group">
                    <label>Description</label>
                    <textarea name="Description" class="form-control" placeholder="Enter Accomodation Type Description..."></textarea>
                </div>
            </form>
            <div id="errorDiv">
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" id="actionButton" class="btn btn-primary">Save changes</button>
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        </div>
    </div>
}

这是Save Changes 按钮的脚本

<script>
   $("#actionButton").click(function () {
        $.ajax({
            url: '@Url.Action("Action", "AccomodationTypes")',
            type: "post",
            data: $("actionForm").serialize()
        })
            .done(function (response) {
                debugger;
                if (response.Success) {
                    location.reload();
                }
                else {
                    $(".errorDiv").html(response.Message)
                }
            });
    });
</script>

【问题讨论】:

    标签: json ajax asp.net-mvc database


    【解决方案1】:

    由于您使用的是 $("actionForm").serialize() 您必须将模型绑定到表单输入控件:

       <input type="text"  asp-for"@Model.Name" name="Name" class="form-control" 
    placeholder="Enter Accomodation Type Name..."> 
    // or you can try to replace asp-for by value="@model.Name" 
             
    <textarea  asp-for="@Model.Description"  name="Description" class="form-control" 
    placeholder="Enter Accomodation Type Description..."></textarea>
                   
    

    或者,如果您使用旧版本的 MVC,您可以尝试将您的输入控件替换为:

    @Html.TextBoxFor(m => m.Name, new { @class = "form-control" })   
    @Html.TextAreaFor(m => m.Description, new { @class = "form-control" })   
    

    而且你也有一个 javascript 错误。替换

    $("actionForm").serialize()
    

    $("#actionForm").serialize()
    

    甚至更好:

    $("#actionForm").serializeArray()
    

    【讨论】:

    • 使用$("actionForm").serialize() 时,我还需要使用调试器、调试菜单或浏览器控制台中的“附加到进程”选项做些什么吗?
    • @KDeven 你有另一个错误。请参阅我的更新答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多