简体   繁体   English

如何在 .NET Core Razor Pages 的级联下拉列表中重置值

[英]How to reset value in a cascading dropdown in .NET Core Razor Pages

I'm new to whole .NET Core thing, I was using ASP.NET 4 (Forms) for many year.我是整个 .NET Core 的新手,我使用 ASP.NET 4(表单)很多年了。 I probably just can't think properly or I miss something obvious.我可能只是无法正确思考,或者我错过了一些明显的东西。

I have 3 classes:我有3个班级:

public class Rat {
    public int RatId { get; set; }
    public string Name { get; set; }
    public Color Color { get; set; }
    public int ColorId { get; set; }
    public ColorAddition ColorAddition {get;set;}
    public int? ColorAdditionId { get; set; }
    }
public class Color {
    public int ColorId { get; set; }
    public string Name { get; set; }
    public bool Addition { get; set; }
    }
public class ColorAddition {
    public int ColorAdditionId { get; set; }
    public string Name { get; set; }
 }

Every rat must have a color and can have color addition.每只老鼠都必须有颜色,并且可以添加颜色。 Some Colors have Color Additions (all colors with color additions have the same subset of color additions).某些颜色具有颜色添加(所有添加颜色的颜色都具有相同的颜色添加子集)。 If the rat have color with color addition, you need to specify that addition, otherwise it can be null.如果老鼠有颜色加色,则需要指定该加色,否则可以为空。

I created CRUD for the rat class.我为老鼠类创建了 CRUD。 The update view looks like this:更新视图如下所示:

<div class="row">
    <div class="col-md-4">
        <form method="post">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="Rat.RatId" />
            <div class="form-group">
                <label asp-for="Rat.Name" class="control-label"></label>
                <input asp-for="Rat.Name" class="form-control" />
                <span asp-validation-for="Rat.Name" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="Rat.ColorId" class="control-label"></label>
                <select asp-for="Rat.ColorId" class="form-control" asp-items="ViewBag.ColorId"></select>
                <span asp-validation-for="Rat.ColorId" class="text-danger"></span>
            </div>
            <div class="form-group">
                <div id="ColorAddition">
                        <label asp-for="Rat.ColorAdditionId" class="control-label"></label>
                        <select asp-for="Rat.ColorAdditionId" class="form-control" asp-items="ViewBag.ColorAdditionId">
                            <option  disabled selected>Zvolte</option>
                        </select>
                        <span asp-validation-for="Rat.ColorAdditionId" class="text-danger"></span>
               </div>
            </div>

It consists of two select lists, one for Color, another one for color addition.它由两个选择列表组成,一个用于颜色,另一个用于颜色添加。 When the color have color addition, I would like to display Color addition list, otherwise it should be hidden.当颜色有颜色添加时,我想显示颜色添加列表,否则应该隐藏。 So I created this at the end of the view:所以我在视图的末尾创建了这个:

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
    $('#Rat_ColorId').change(function () {
        var selectedColor = $("#Rat_ColorId").val();

        $.getJSON(`?handler=HaveColorAddition&id=${selectedColor}`, function (emp) {
            console.log(emp);
            if (emp == true)
            {
                $('#ColorAddition').show();

            }
            else
            {
                $('#ColorAddition').hide();
                $('#Rat_ColorAdditionId').val(null);

            }

        });
    });

</script>
}

It calls Json, which is returning true if the color have color addition and false if not:它调用 Json,如果颜色有颜色添加,则返回 true,否则返回 false:

public JsonResult OnGetHaveColorAddition(int id)
        {
            return new JsonResult(_context.Colors.Find(id).Addition);
        }

So far so good, this is working as intended.到目前为止一切顺利,这是按预期工作的。 If I choose color without color addition, the color addition select list is hidden and its value is null.如果我选择没有颜色添加的颜色,则颜色添加选择列表被隐藏并且其值为空。

The trouble is that if I update the form now, color addition is not empty, but it keeps the previous value.麻烦的是,如果我现在更新表单,颜色添加不是空的,而是保留以前的值。

Example: I have blue color (with color addition light and dark) and black color (without color addition).示例:我有蓝色(添加颜色的浅色和深色)和黑色(不添加颜色)。 Right now the color is blue and addition is light.现在颜色是蓝色,添加是浅色。 I want to change color to black, so I choose black.我想把颜色改成黑色,所以我选择了黑色。 Select list with addition is hidden now and without a value.添加的选择列表现在隐藏并且没有值。 Once I submit the form, color is changed to black but addition is still light.提交表单后,颜色变为黑色,但添加仍然浅。

Update code looks like this:更新代码如下所示:

public async Task<IActionResult> OnPostAsync(int? id)
    {
        if (!ModelState.IsValid)
        {
            return Page();
        }

        var ratToUpdate = await _context.Rats.FindAsync(id);

        if (ratToUpdate == null)
        {
            return NotFound();
        }

        if (await TryUpdateModelAsync<Rat>(
        ratToUpdate,
        "rat",
        r => r.Name, r =>r.ColorId, r => r.ColorAdditionId))
        {
            await _context.SaveChangesAsync();
            return RedirectToPage("./Index");
        }
        return Page();
    }

What am I doing wrong?我究竟做错了什么?

When you post data to handler , you just post Rate id to server side , and still query the database to base on id :当您将数据发布到处理程序时,您只需将 Rate id 发布到服务器端,并且仍然基于 id 查询数据库:

var ratToUpdate = await _context.Rats.FindAsync(id);

So that the ColorAdditionId is always the one which stored in database .因此ColorAdditionId始终是存储在数据库中的那个。 You should include the Rat.ColorAdditionId when page posting data to OnPostAsync handler , so that server side can update the ColorAdditionId and save to database , and show new value after return RedirectToPage("./Index");您应该在页面将数据发布到OnPostAsync处理程序时包含Rat.ColorAdditionId ,以便服务器端可以更新ColorAdditionId并保存到数据库,并在return RedirectToPage("./Index");后显示新值return RedirectToPage("./Index"); which will query the datbabase to get the newest value .这将查询 datbabase 以获取最新值。

Please refer to below documents for how to use Forms in Razor Pages :有关如何在 Razor Pages 中使用表单,请参阅以下文档:

https://www.learnrazorpages.com/razor-pages/forms https://www.learnrazorpages.com/razor-pages/forms

https://docs.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-3.1&tabs=visual-studio https://docs.microsoft.com/en-us/aspnet/core/razor-pages/?view=aspnetcore-3.1&tabs=visual-studio

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM