简体   繁体   中英

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. I probably just can't think properly or I miss something obvious.

I have 3 classes:

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. 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:

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 :

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

So that the ColorAdditionId is always the one which stored in database . 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"); which will query the datbabase to get the newest value .

Please refer to below documents for how to use Forms in Razor Pages :

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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