You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在MVC中从控制器向视图传递文本消息或跳转链接

MVC 框架下短链生成结果展示的规范实现方案

一、控制器端逻辑调整

你原有代码中ViewBag.ShortenURLSuccess(xxx)的写法不符合ViewBag的使用规范(ViewBag是动态数据字典,不可作为方法调用),需要调整为状态标识+内容分离的存储逻辑,同时直接在服务端生成完整短链,避免前端拼接出现路径错误:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ShortenURL(ShortURLModel model)
{
    if(ModelState.IsValid)
    {
        if(_shortUrlProcessor.CreateShortURL(model.originalURL, model.shortURL))
        {
            // 生成完整的绝对路径短链,参数自行替换为你的跳转路由规则
            string fullShortUrl = Url.Action("RedirectToOrigin", "ShortUrl", new { code = model.shortURL }, Request.Url.Scheme);
            ViewBag.IsSuccess = true;
            ViewBag.ResultContent = fullShortUrl;
        }
        else
        {
            ViewBag.IsSuccess = false;
            ViewBag.ResultContent = "无法生成短链接,请检查自定义短链是否已被占用";
        }
    }
    else
    {
        ViewBag.IsSuccess = false;
        ViewBag.ResultContent = "输入参数不合法,请检查填写的原始链接和自定义短链格式";
    }          
    return View(model);
}

二、同步提交场景视图实现

在表单提交按钮下方添加结果渲染区域,通过Razor语法判断状态,渲染对应内容:

@model ShortURLModel

@using (Html.BeginForm("ShortenURL", "ShortUrl", FormMethod.Post))
{
    @Html.AntiForgeryToken()
    <!-- 原有表单字段代码省略 -->
    
    <button type="submit" class="btn btn-primary">生成短链</button>

    <!-- 结果展示区域 -->
    @if (ViewBag.IsSuccess != null)
    {
        if (ViewBag.IsSuccess)
        {
            <div class="text-success mt-2">
                生成成功:<a href="@ViewBag.ResultContent" target="_blank">@ViewBag.ResultContent</a>
            </div>
        }
        else
        {
            <div class="text-danger mt-2">
                @ViewBag.ResultContent
            </div>
        }
    }
}

注:text-danger、mt-2为Bootstrap内置样式,你也可以自定义红色提示的CSS样式。

三、可选:无刷新提交方案(体验更优)

如果不需要页面整体刷新,可以改用AJAX提交表单,控制器返回JSON结果,前端动态渲染内容:

控制器调整为返回JSON

[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult ShortenURL(ShortURLModel model)
{
    if(ModelState.IsValid)
    {
        if(_shortUrlProcessor.CreateShortURL(model.originalURL, model.shortURL))
        {
            string fullShortUrl = Url.Action("RedirectToOrigin", "ShortUrl", new { code = model.shortURL }, Request.Url.Scheme);
            return Json(new { isSuccess = true, content = fullShortUrl });
        }
        else
        {
            return Json(new { isSuccess = false, content = "无法生成短链接,请检查自定义短链是否已被占用" });
        }
    }
    return Json(new { isSuccess = false, content = "输入参数不合法,请检查填写内容" });
}

前端AJAX提交代码

// 拦截表单提交事件
$('form').submit(function(e) {
    e.preventDefault();
    $.post($(this).attr('action'), $(this).serialize(), function(res) {
        const resultContainer = $('#result-container');
        if (res.isSuccess) {
            resultContainer.html(`<div class="text-success mt-2">生成成功:<a href="${res.content}" target="_blank">${res.content}</a></div>`);
        } else {
            resultContainer.html(`<div class="text-danger mt-2">${res.content}</div>`);
        }
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:06:02