【问题标题】:Ajax post method works with problem, in asp.net core projectAjax post方法在asp.net核心项目中存在问题
【发布时间】:2021-07-22 15:11:40
【问题描述】:

我在 asp.net 核心中有一个代码,它从数据库的“颜色”表中读取所有行(在 SQL 服务器中)并在数据表中显示这些数据。在该表上方,点击后有一个按钮,会打开一个手风琴并显示一个可以在下表中插入新行的表单。

我有一个名为“ColorController”的控制器,它有 3 个动作:ShowColors、Insert(get mode)、Insert(post mode)。

ColorController.cs

    private IColor _icolor;

    public ColorController(IColor icolor)
    {
        _icolor = icolor;
    }

    public IActionResult ShowColors()
    {
        return View(_icolor.ShowColors());
    }

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

    [HttpPost]
    public IActionResult Insert(ColorViewModel colorViewModel)
    {
        if (ModelState.IsValid)
        {
            if (_icolor.isColorExist(colorViewModel.ColorCode))
            {
                ViewBag.Validation = 1;
                ModelState.AddModelError("ColorCode", "Exist!");
                return View(colorViewModel);
            }
            else
            {
                ViewBag.Validation = 0;    
                
                // ... Insert codes

                return RedirectToAction("ShowColors","Color");                   
            }
        }
        else
        {
            ViewBag.Validation = 1;
            return View(colorViewModel);
        }
    }

我为颜色控制器的操作编写了 2 个视图。这些观点:

ShowColors.cshtml:

@model IEnumerable<DataAccessLayer.Entities.Color>

<div class="card">
    <div class="card-body">
        <div class="accordion">
            <div class="accordion-row">
                <a class="accordion-header" href="#">
                    <button type="button" onclick='Insert() >
                        InsertColor
                    </button>
                </a>
                <div class="accordion-body" id="InsertForm">

                </div>
            </div>
        </div>
    </div>
</div>
<div class="card">
    <div class="card-body">
            <table id="example" class="table table-hover">

              @*...Show datatable...*@

            </table>
        </div>
    </div>
</div>
<script>
   function Insert() {
       var _url = '@Url.Action("Insert", "Color")';
        $.ajax({
           url: _url,
           type: "Get",
           data: {}
        }).done(function (result) {
           $('#InsertForm').html(result);
        });
    }
</script>

Insert.cshtml(我使用“IsValid”输入进行检查验证。)

<div class="card">
    <div class="card-body">
        <form>
            <input name="IsValid" type="hidden" value="@ViewBag.Validation" id="validation" />
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-row">
                <div class="col-md-6 mb-3">
                    <div class="form-group">
                        <label asp-for="ColorCode" class="control-label"></label>
                        <input asp-for="ColorCode" class="form-control" id="txtColorCode" />
                        <span asp-validation-for="ColorCode" class="text-danger"></span>
                    </div>
                </div>
                <div class="col-md-6 mb-3">
                    <div class="form-group">
                        <label asp-for="ColorName" class="control-label"></label>
                        <input asp-for="ColorName" class="form-control" id="txtColorName" />
                        <span asp-validation-for="ColorName" class="text-danger"></span>
                    </div>
                </div>
            </div>

            <div class="form-group">
                    <div class="ml-3 mt-3">
                        <button type="submit" onclick='InsertColor()' >Add Color</button>
                    </div>
            </div>
        </form>
    </div>
</div>

<script>
    function InsertColor() {
        var _url = '@Url.Action("Insert", "Color")';
        $.ajax({
            url: _url,
            type: "POST",
            data: {
                ColorCode: $("#txtColorCode").val(),
                ColorName: $("#txtColorName").val(),
            },
            success: function (response) {
                $('#InsertForm').html(response);
                var isValid = $('body').find('[name="IsValid"]').val();
                if (isValid == 1) {
                    stop();
                }
            },
            complete: function (xhr, status) {
                var isValid = $('body').find('[name="IsValid"]').val();
                console.log("Is valid =" + isValid);
                if (isValid != 1)
                {
                    if (status == 'success')
                        window.location.href = '@Url.Action("ShowColors", "Color")';
                }
            },
        }).done(function (result) {
            $('#InsertForm').html(result);
                var isValid = $('body').find('[name="IsValid"]').val();
                if (isValid != 1) {
                    window.location.href = '@Url.Action("ShowColors", "Color")';
            }
        });
    }
</script>

当我运行代码时,一切正常,直到我想插入新颜色。 GET 模式(插入操作)工作正常,但 POST 模式有问题。在我第一次添加新颜色和模型状态无效时,代码不起作用。下次,如果模型状态有效,则在数据库中插入新行,但在“ShowColors”视图的表中看不到。我在代码中重新加载 showColors 动作,但在地址栏中,地址有参数,如下所示:

localhost:.../Color/ShowColors?IsValid=&ColorCode=pur&ColorName=purple

虽然我想展示这个:

localhost:.../Color/ShowColors

我猜“插入”视图中的 ajax 函数是错误的,但我找不到错误。谁能帮帮我,问题出在哪里?

【问题讨论】:

    标签: javascript c# jquery ajax asp.net-core


    【解决方案1】:

    当我运行代码时,一切正常,直到我想插入新颜色。 GET 模式(插入操作)工作正常,但 POST 模式有问题。在 我第一次添加新颜色和模型状态无效, 代码不起作用。在下一次,如果模型状态有效,新行 插入数据库,但在“ShowColors”视图的表中看不到。一世 在代码中重新加载 showColors 动作,但在地址栏中,地址有 参数,

    请检查Insert.cshtml 中的代码,我已经在我的示例中检查过,似乎它会通过提交按钮触发默认提交操作,并且 JavaScript 脚本不起作用。如果我在 ShowColors 页面中移动 JavaScript 脚本,JavaScript 脚本可以工作,但是由于您使用的是done()complete() 方法,在 ajax 成功函数之后,它会触发该函数并刷新主页。

    通过Ajax插入新颜色成功后,在Ajax成功函数中,我们可以使用JQuery将新颜色添加到颜色列表中,或者使用Ajax方法调用action方法更新颜色表内容。

    您可以参考以下示例代码:用户局部视图显示颜色列表并插入新颜色。

    型号:

    public class Color
    {
        public int ColorID { get; set; }
        public string ColorCode { get; set; }
        public string ColorName { get; set; }
    }
    public class ColorViewModel
    {
        public string ColorCode { get; set; }
        public string ColorName { get; set; }
    }
    

    PVInsert.cshtml:用于插入新颜色

    @model WebApplication1.Models.ColorViewModel
    
    @{
        ViewData["Title"] = "Insert";
        Layout = "";
    }
    <div class="card">
        <div class="card-body">
            <form asp-action="Insert">
                <input name="IsValid" type="hidden" value="@ViewBag.Validation" id="validation" />
    
                <div asp-validation-summary="ModelOnly" class="text-danger"></div>
                <div class="form-row">
                    <div class="col-md-6 mb-3">
                        <div class="form-group">
                            <label asp-for="ColorCode" class="control-label"></label>
                            <input asp-for="ColorCode" class="form-control" id="txtColorCode" />
                            <span asp-validation-for="ColorCode" class="text-danger"></span>
                        </div>
                    </div>
                    <div class="col-md-6 mb-3">
                        <div class="form-group">
                            <label asp-for="ColorName" class="control-label"></label>
                            <input asp-for="ColorName" class="form-control" id="txtColorName" />
                            <span asp-validation-for="ColorName" class="text-danger"></span>
                        </div>
                    </div>
                </div>
    
                <div class="form-group">
                    <div class="ml-3 mt-3">
                        <button type="button" id="btnaddcolor">Add Color</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
    

    _PVShowAllColor.cshtml:用于显示颜色列表。

    @model IEnumerable<WebApplication1.Models.Color>
    <table id="example" class="table table-hover">
        <thead>
            <tr>
                <th>
                    @Html.DisplayNameFor(model => model.ColorID)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.ColorCode)
                </th>
                <th>
                    @Html.DisplayNameFor(model => model.ColorName)
                </th>
                <th></th>
            </tr>
        </thead>
        <tbody>
            @foreach (var item in Model)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.ColorID)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.ColorCode)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.ColorName)
                    </td>
                    <td>
                        @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
                        @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
                        @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
                    </td>
                </tr>
            }
        </tbody>
    </table> 
    

    ShowColors.cshtml:

    @model IEnumerable<WebApplication1.Models.Color>
    
    @{
        ViewData["Title"] = "ShowColors";
    }
    
    
    <div class="card">
        <div class="card-body">
            <div class="accordion">
                <div class="accordion-row">
                    <a class="accordion-header" href="#">
                        <button type="button" onclick='Insert()'>
                            InsertColor
                        </button>
                    </a>
                    <div class="accordion-body" id="InsertForm">
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div class="card">
        <div class="card-body">
            <div id="colorlist"> 
                <partial name="_PVShowAllColor" model="@Model" />
            </div>
        </div>
    </div> 
    <script>
        function Insert() {
            event.preventDefault();
           var _url = '@Url.Action("Insert", "Color")';
            $.ajax({
               url: _url,
               type: "Get",
               data: {}
            }).done(function (result) {
                $('#InsertForm').html(result);
                Addcolor();
            });
        }
    
        function Addcolor() {
              //find the add color button in the InsertForm, and then insert the new color.
                $("#btnaddcolor").click(function () {
                    event.preventDefault();
                    var _url = '@Url.Action("Insert", "Color")';
                    $.ajax({
                        url: _url,
                        type: "POST",
                        data: {
                            ColorCode: $("#txtColorCode").val(),
                            ColorName: $("#txtColorName").val(),
                        },
                        success: function (response) {
                            //update the Insert Form.
                            $('#InsertForm').html(response);
                            //attach the click event for the AddColor button.
                            Addcolor();
                            var isValid = $('body').find('[name="IsValid"]').val();
                            if (isValid == 1) {
                                stop();
                            }
                            //after insert the new color success, call the ShowAllColor action method to update the partial view (display the latest data)
                            $.ajax({
                                url: '@Url.Action("ShowAllColor", "Color")',
                                type: "Get",
                                success: function (responsedata) {
                                    $('#colorlist').html(responsedata);
                                }
                            });
                        },
                    });
                });
        }
    </script>
    

    颜色控制器:

    public class ColorController : Controller
    {
        private readonly ApplicationDbContext _context;
        public ColorController(ApplicationDbContext context)
        {
            _context = context;
        }
    
        public IActionResult ShowColors()
        {  
            return View(_context.Colors.ToList());
        }
    
        public IActionResult ShowAllColor()
        {
            return PartialView("_PVShowAllColor",_context.Colors.ToList());
        }
    
        public IActionResult Insert()
        {
            var newcolor = new ColorViewModel();
            return PartialView("_PVInsert", newcolor);
        }
    
        [HttpPost]
        public IActionResult Insert(ColorViewModel colorViewModel)
        {
            if (ModelState.IsValid)
            {
                if (_context.Colors.Any(c => c.ColorCode == colorViewModel.ColorCode))
                {
                    ViewBag.Validation = 1;
                    ModelState.AddModelError("ColorCode", "Exist!");
                    return PartialView("_PVInsert", colorViewModel);
                }
                else
                {
                    ViewBag.Validation = 0;
    
                    var newcolor = new Color() { ColorCode = colorViewModel.ColorCode, ColorName = colorViewModel.ColorName };
                    _context.Colors.Add(newcolor);
                    _context.SaveChanges();
    
                    var newcolorvm = new ColorViewModel();
                    return PartialView("_PVInsert", newcolorvm);
                }
            }
            else
            {
                ViewBag.Validation = 1;
                return PartialView("_PVInsert", colorViewModel);
            }
        }
    }
    

    结果如下:

    【讨论】:

    • 非常感谢...我的错误是“AddColor”按钮的类型!它必须是“按钮”,而不是“提交”!我完全忘记了,并认为问题出在 ajax 代码中......再次感谢 n。
    猜你喜欢
    • 2019-09-17
    • 2020-08-27
    • 2021-10-04
    • 2019-07-29
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    相关资源
    最近更新 更多