Javascript 在asp.net核心项目中,Ajax post方法解决了这个问题

Javascript 在asp.net核心项目中,Ajax post方法解决了这个问题,javascript,c#,jquery,ajax,asp.net-core,Javascript,C#,Jquery,Ajax,Asp.net Core,我在asp.NETCore中有一个代码,它从数据库的“Color”表(在SQLServer中)读取所有行,并在数据表中显示这些数据。在该表上方,单击后有一个按钮,打开一个手风琴,显示一个可以在表下方插入新行的表单 我有一个名为“ColorController”的控制器,它有3个动作:显示颜色、插入(获取模式)、插入(发布模式) ColorController.cs: private IColor _icolor; public ColorController(IColor ic

我在asp.NETCore中有一个代码,它从数据库的“Color”表(在SQLServer中)读取所有行,并在数据表中显示这些数据。在该表上方,单击后有一个按钮,打开一个手风琴,显示一个可以在表下方插入新行的表单

我有一个名为“ColorController”的控制器,它有3个动作:显示颜色、插入(获取模式)、插入(发布模式)

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);
        }
    }
我为颜色控制器的操作编写了两个视图。这些意见:

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>
@model IEnumerable
@*…显示数据表*@
函数插入(){
var_url='@url.Action(“插入”、“颜色”);
$.ajax({
url:_url,
键入:“获取”,
数据:{}
}).完成(功能(结果){
$('#InsertForm').html(结果);
});
}
Insert.cshtml(我使用“IsValid”输入进行检查验证。)


添加颜色
函数InsertColor(){
var_url='@url.Action(“插入”、“颜色”);
$.ajax({
url:_url,
类型:“POST”,
数据:{
颜色代码:$(“#txtColorCode”).val(),
ColorName:$(“#txtColorName”).val(),
},
成功:功能(响应){
$('#InsertForm').html(响应);
var isValid=$('body').find('[name=“isValid”]').val();
if(isValid==1){
停止();
}
},
完成:功能(xhr,状态){
var isValid=$('body').find('[name=“isValid”]').val();
console.log(“Is valid=“+isValid”);
如果(isValid!=1)
{
如果(状态=‘成功’)
window.location.href='@Url.Action(“ShowColors”、“Color”);
}
},
}).完成(功能(结果){
$('#InsertForm').html(结果);
var isValid=$('body').find('[name=“isValid”]').val();
如果(isValid!=1){
window.location.href='@Url.Action(“ShowColors”、“Color”);
}
});
}
当我运行代码时,一切都正常,直到我想插入新的颜色。GET模式(插入操作)为true,但POST模式存在问题。在我第一次添加新颜色和模型时,状态无效,代码不起作用。在接下来的时间里,若模型状态是有效的,那个么在数据库中但在“ShowColors”视图的表中并没有看到新行插入。我在代码中重新加载ShowColor操作,但在地址栏中,地址有如下参数:

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

我想展示一下:

localhost:…/Color/ShowColors

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

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

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

在通过Ajax插入新颜色success之后,在Ajax success函数中,我们可以使用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>
结果如下:


非常感谢。。。我的错误是“添加颜色”按钮的类型!它必须是“按钮”,而不是“提交”!我完全忘记了,认为问题出在ajax代码中。。。再次感谢你。
@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>
@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> 
@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);
        }
    }
}