You need to enable JavaScript to run this app. ASP.NET Core 5.0 MVC 单选按钮控制复选框组生成Joke API请求URL实现
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 5.0 MVC 单选按钮控制复选框组生成Joke API请求URL实现

实现方案

1. 调整视图模型(ViewModel)

保证字段和表单控件name属性匹配,支持模型自动绑定:

public class JokeRequestURLVM
{
    // 匹配单选按钮name="category",接收Any/Custom选中值
    public string category { get; set; }
    // 匹配复选框name="customcategory",自动接收所有勾选的自定义分类
    public List<string> customcategory { get; set; } = new List<string>();
    
    // 保留原有其他属性
    public string language { get; set; }
    public string format { get; set; }
    public Joke joke { get; set; }
    public Flags flags { get; set; }
    public int amount { get; set; }
}

补充:原有Joke、Flags类不需要修改,保持原有定义即可。

2. 调整视图代码(含交互逻辑)

替换原有表单代码,增加元素ID便于JS控制,补充交互逻辑实现两个场景的状态切换:

@model WebAPIConsume.ViewModels.JokeRequestURLVM

<form method="post" asp-action="GetRequestURL" asp-controller="Jokes">
    <div asp-validation-summary="ModelOnly" class="text-danger"></div>

    <div class="form-group">
        <label class="control-label">选择分类/多个分类</label>
        <!-- Any单选按钮 -->
        <div>
            <input type="radio" name="category" value="Any" id="radioAny" checked="checked" />
            <label for="radioAny">Any</label>
        </div>
        <!-- Custom单选按钮 + 分类复选框 -->
        <div>
            <input type="radio" name="category" value="Custom" id="radioCustom" />
            <label for="radioCustom">Custom:</label>
            <input type="checkbox" name="customcategory" value="Programming" class="custom-cb" disabled /> Programming
            <input type="checkbox" name="customcategory" value="Misc" class="custom-cb" disabled /> Misc
            <input type="checkbox" name="customcategory" value="Dark" class="custom-cb" disabled /> Dark
            <input type="checkbox" name="customcategory" value="Pun" class="custom-cb" disabled /> Pun
            <input type="checkbox" name="customcategory" value="Spooky" class="custom-cb" disabled /> Spooky
            <input type="checkbox" name="customcategory" value="Christmas" class="custom-cb" disabled /> Christmas
        </div>
    </div>

    <button type="submit" class="btn btn-primary">生成请求URL</button>
</form>

<!-- 生成的URL展示区域 -->
@if (ViewBag.GeneratedUrl != null)
{
    <div class="alert alert-success mt-3">
        生成的请求地址:<code>@ViewBag.GeneratedUrl</code>
    </div>
}

<!-- 交互JS -->
<script>
const radioAny = document.getElementById('radioAny');
const radioCustom = document.getElementById('radioCustom');
const customCbs = document.querySelectorAll('.custom-cb');

// 切换复选框状态
function toggleCbs() {
    if (radioAny.checked) {
        // 选Any:禁用所有复选框,清空选中状态
        customCbs.forEach(cb => {
            cb.disabled = true;
            cb.checked = false;
        });
    } else if (radioCustom.checked) {
        // 选Custom:启用所有复选框
        customCbs.forEach(cb => cb.disabled = false);
    }
}

// 页面加载时初始化状态,绑定事件
toggleCbs();
radioAny.addEventListener('click', toggleCbs);
radioCustom.addEventListener('click', toggleCbs);
</script>

说明:去掉了原表单无用的enctype="multipart/form-data"属性,因为无文件上传需求,减少不必要的请求开销。

3. 控制器逻辑(生成请求URL)

在原有JokesController中补充POST方法重载,接收表单提交数据并拼接符合要求的请求地址:

public class JokesController : Controller
{
    // 原有GET方法,返回表单视图
    [HttpGet]
    public IActionResult GetRequestURL()
    {
        return View();
    }

    // 新增POST方法,处理表单提交、生成请求URL
    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult GetRequestURL(JokeRequestURLVM model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        const string apiBase = "https://v2.jokeapi.dev/joke/";
        string categoryPath;

        // 处理分类路径
        if (model.category == "Any")
        {
            categoryPath = "Any";
        }
        else
        {
            // 自定义模式下校验是否勾选分类
            if (model.customcategory == null || model.customcategory.Count == 0)
            {
                ModelState.AddModelError(nameof(model.customcategory), "请至少勾选一个自定义分类");
                return View(model);
            }
            // 勾选的分类用逗号拼接
            categoryPath = string.Join(",", model.customcategory);
        }

        // 拼接完整请求地址,后续可追加其他筛选参数(语言、格式等)作为查询字符串
        string fullUrl = $"{apiBase}{categoryPath}";
        
        // 将生成的URL传递给视图展示
        ViewBag.GeneratedUrl = fullUrl;

        return View(model);
    }
}

4. 效果验证

  • 选中Any单选:所有分类复选框自动禁用,提交后生成的请求地址为https://v2.jokeapi.dev/joke/Any,符合场景2要求。
  • 选中Custom单选:所有分类复选框自动启用,勾选Programming、Misc后提交,生成的请求地址为https://v2.jokeapi.dev/joke/Programming,Misc,符合场景1要求。

内容的提问来源于stack exchange,提问作者user9555045

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.05 13:54:06