ASP.NET Core MVC - 单选按钮选择在编辑期间不保留

问题描述 投票:0回答:1

我正在开发一个 ASP.NET Core MVC 应用程序,用户可以在其中管理类别。我有一个用于创建和编辑类别的部分视图 (

_AddOrEditModal.cshtml
)。该部分视图包括用于选择类别
Type
“费用”“收入”)的单选按钮。

我面临的问题是,在编辑现有类别时,我无法更改

Type
属性的选定单选按钮。单选按钮根据
Model.Type
的当前值正确显示,但在编辑过程中我根本无法选择其他选项。例如,如果类别的类型为“费用”,则预先选择“费用”单选按钮,但我无法单击“收入”单选按钮来切换它。它只是对点击没有反应。只能更改
Model.Name
的值

有趣的是,相同的表单,但放置在单独的完整视图(而不是弹出/模式)中,并且仅用于编辑操作的单独控制器,效果很好。在那里我可以自由更改单选按钮选择。

相关代码如下:

局部视图(
_AddOrEditModal.cshtml
)

@model LabProject.Models.Category

@{
    string idContent;
    string headingContent;
    string submitContent;

    if (Model.Id == 0) {
        idContent = "AddOrEditModal";
        headingContent = "Create new category";
        submitContent = "Create";
    } 
    else 
    {
        idContent = $"AddOrEditModal-{Model.Id}";
        headingContent = "Edit your category";
        submitContent = "Edit";
    }
}


<div class="modal fade" id="@idContent" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header flex-wrap">
                <h5 class="modal-title mb-3" id="exampleModalLabel2">@headingContent</h5>
                
                <button type="button"
                        class="btn-close"
                        data-bs-dismiss="modal"
                        aria-label="Close"></button>

                <form id="categoryForm" asp-action="AddOrEdit" method="post">
                    <input type="hidden" asp-for="Id" />
                    <div asp-validation-summary="ModelOnly" class="text-danger"></div>

                    
                    <div class="d-flex gap-2 mb-3">
                        <input type="radio" class="btn-check" name="Type" id="expenseRadio" value="Expense" asp-for="Type"
                         />
                        <label class="btn btn-outline-secondary" for="expenseRadio">
                            Expense
                        </label>
                       
                        <input type="radio" class="btn-check" name="Type" id="incomeRadio" value="Income" asp-for="Type"
                         />
                        <label class="btn btn-outline-secondary" for="incomeRadio">
                            Income
                        </label>
                    </div>

                    <div class="form-group mb-3">
                        <label asp-for="Name" class="control-label"></label>
                        <input asp-for="Name" class="form-control" />
                        <span asp-validation-for="Name" class="text-danger"></span>
                    </div>
                    <div class="form-group">

                        <input type="submit" value="@submitContent" class="btn btn-primary mb-4" />
                    </div>
                </form>

            </div>
        </div>
    </div>
</div>


@section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
    }
}

控制器(添加或编辑操作):

// GET: CategoryController/AddOrEdit
public IActionResult AddOrEdit(int? id)
{
    
    if (id == null)
    {                
        return PartialView("_AddOrEditModal", new Category());
    } else
    {
        Category category = _context.Categories.Find(id);
        
        return PartialView("_AddOrEditModal",category);
    }
    
}

// POST: CategoryController/AddOrEdit
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> AddOrEdit([Bind("Id,Name,IsDefault, UserId, Type")] Category category)
{
    var user = await _userManager.GetUserAsync(User);
    if (user == null)
    {
        return RedirectToAction("Login", "Account");
    }

    

    if (ModelState.IsValid)
    {
        try
        {
            category.UserId = user.Id.ToString();
            if (category.Id == 0)
            {
                _context.Categories.Add(category);
            }
            else
            {
                _context.Categories.Update(category);
            }

            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(CategoryList));
        }
        catch (Exception ex)
        {
            TempData["ErrorMessage"] = $"An error occurred: {ex.Message}";
        }
    }
    var categories = await _context.Categories
        .Where(c => c.UserId == user.Id)
        .ToListAsync();
    //return View("CategoryList", categories);
    return PartialView("_AddOrEditModal", category);
}

Type
属性包含在
[Bind]
属性中,我使用
asp-for
作为单选按钮。但是,我什至无法在编辑时选择替代单选按钮。

这可能是什么原因造成的?我该如何解决?任何帮助将不胜感激。

asp.net-core controller asp.net-core-mvc radio-button
1个回答
0
投票

基于您的代码的最小示例,在我这边运行良好:

型号:

public class ViewModel
{
    public string? Name { get; set; }
    public string Type { get;set; }

    public int Id { get; set; }
}

查看:

索引页:

<button id="myBtn" class="btn btn-primary btn-sm">Open Modal</button>



<partial name="Partial" model="@new ViewModel()"></partial>


<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
    $("#myBtn").click(function(){
        $("#exampleModal").modal("show");
    })

</script>

局部视图:

@model ViewModel


<div class="modal fade" id="exampleModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header flex-wrap">
                <h5 class="modal-title mb-3" id="exampleModalLabel2">Head</h5>

                <button type="button"
                        class="btn-close"
                        data-bs-dismiss="modal"
                        aria-label="Close"></button>

                <form id="categoryForm" asp-action="AddOrEdit" method="post">
                    <input type="hidden" asp-for="Id" />
                    <div asp-validation-summary="ModelOnly" class="text-danger"></div>


                    <div class="d-flex gap-2 mb-3">
                        <input type="radio" class="btn-check" name="Type" id="expenseRadio" value="Expense" asp-for="Type" />
                        <label class="btn btn-outline-secondary" for="expenseRadio">
                            Expense
                        </label>

                        <input type="radio" class="btn-check" name="Type" id="incomeRadio" value="Income" asp-for="Type" />
                        <label class="btn btn-outline-secondary" for="incomeRadio">
                            Income
                        </label>
                    </div>

                    <div class="form-group mb-3">
                        <label asp-for="Name" class="control-label"></label>
                        <input asp-for="Name" class="form-control" />
                        <span asp-validation-for="Name" class="text-danger"></span>
                    </div>
                    <div class="form-group">

                        <input type="submit" value="Submit" class="btn btn-primary mb-4" />
                    </div>
                </form>

            </div>
        </div>
    </div>
</div>

控制器:

public IActionResult Index()
{
    return View();
}
[HttpPost]
public IActionResult AddOrEdit(ViewModel vm)
{
    return Ok();
}

结果:

enter image description here

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.