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

ASP.NET视图传字符串参数及模型自动赋值问题

ASP.NET 问题解决方案

1. 参数传递问题解决方法

你在控制器中已将nombreSeguidor存入ViewBag,但视图无法调用的核心原因是视图未正确引用ViewBag,或模型配置与传递逻辑不匹配。

修复步骤:

  1. 直接调用ViewBag取值:在Create.cshtml中使用@ViewBag.nombreSeguidor获取参数,比如修改显示文本:
<p>Crear saludo para @ViewBag.nombreSeguidor</p>
  1. (可选)用模型传递参数:如果更倾向通过模型接收,修改控制器返回语句:
// GET: Saludos/Create
public ActionResult Create(string nombreSeguidor)
{
    ViewBag.Seguidores_Id = new SelectList(_repositorioSeguidores.DameTodo(), "Id", "NombreTwitch");
    // 将参数作为模型传递给视图
    return View(nombreSeguidor);
}

此时视图中@Model即可直接获取nombreSeguidor的值,不影响ViewBag的使用。

2. 模型自动赋值问题解决方法

要实现Id自动生成、固定CreadoPor、自动匹配Seguidores_Id,仅开放Saludo编辑,需从模型配置、视图调整、POST控制器逻辑三方面修改:

第一步:配置模型自动生成Id

在Saludos模型的Id属性添加特性,让EF自动生成主键:

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

public class Saludos
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)] // 自动生成Id
    public int Id { get; set; }
    public string Saludo { get; set; }
    public string CreadoPor { get; set; }
    public Nullable<int> Seguidores_Id { get; set; }
}

第二步:调整视图,仅保留可编辑字段

修改Create.cshtml,隐藏无需编辑的字段,只保留Saludo输入框:

@model TwitchWebApi.Models.Saludos <!-- 恢复使用Saludos模型 -->

@{
    ViewBag.Title = "Create";
}

<h2>Create</h2>

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Saludos</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        <!-- 显示目标用户 -->
        <p>Crear saludo para @ViewBag.nombreSeguidor</p>

        <!-- 仅保留Saludo可编辑字段 -->
        <div class="form-group">
            @Html.LabelFor(model => model.Saludo, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Saludo, new { htmlAttributes = new { @class = "form-control", required = "required" } })
                @Html.ValidationMessageFor(model => model.Saludo, "", new { @class = "text-danger" })
            </div>
        </div>

        <!-- 隐藏字段:自动赋值的Seguidores_Id和CreadoPor -->
        @Html.HiddenFor(model => model.Seguidores_Id)
        @Html.HiddenFor(model => model.CreadoPor)

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Crear" class="btn btn-default" />
            </div>
        </div>
    </div>
}

第三步:在POST控制器中完成自动赋值逻辑

修改Create的POST方法,处理参数匹配和固定值设置:

// POST: Saludos/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Saludos saludos, string nombreSeguidor)
{
    if (ModelState.IsValid)
    {
        // 1. 根据nombreSeguidor查询对应的Seguidores_Id
        var seguidor = _repositorioSeguidores.DameTodo().FirstOrDefault(s => s.NombreTwitch == nombreSeguidor);
        if (seguidor != null)
        {
            saludos.Seguidores_Id = seguidor.Id;
        }

        // 2. 设置固定的CreadoPor值
        saludos.CreadoPor = "固定值"; // 替换为实际固定内容,比如当前登录用户名

        // 3. Id由EF自动生成,无需手动赋值
        _repositorioSaludos.Agregar(saludos);
        return RedirectToAction("Index");
    }

    // 验证失败时重新传递数据
    ViewBag.nombreSeguidor = nombreSeguidor;
    ViewBag.Seguidores_Id = new SelectList(_repositorioSeguidores.DameTodo(), "Id", "NombreTwitch", saludos.Seguidores_Id);
    return View(saludos);
}

同时更新GET方法,传递参数并初始化空模型:

// GET: Saludos/Create
public ActionResult Create(string nombreSeguidor)
{
    ViewBag.nombreSeguidor = nombreSeguidor;
    ViewBag.Seguidores_Id = new SelectList(_repositorioSeguidores.DameTodo(), "Id", "NombreTwitch");
    return View(new Saludos());
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 22:27:33