【问题标题】:Html Helper to get values from Model StateHtml Helper 从模型状态中获取值
【发布时间】:2025-12-07 20:30:01
【问题描述】:

Asp.Net MVC 3

我似乎遇到了与 Darin Dimitrov 回答的这篇文章类似的问题。所以,达林,如果你正在阅读这篇文章,请帮忙:)

asp.net-mvc2 - Strongly typed helpers not using Model?

我遇到的问题是我正在寻找一个包含模型状态中发布的值的 html 助手。

例如,如果我使用这样的编辑器:

@Html.EditorFor(model => model.SelectedTags)

我可以看到发布的值。问题是我需要一种在不创建文本框的情况下获取此值的方法,我只想要字符串,因为我需要在一些 javascript 中使用它。

我尝试过 DisplayFor,但它不包含发布的值:

@Html.DisplayFor(model => model.SelectedTags)

顺便说一句,我觉得这种行为一点也不直观。我花了几个小时从 MVCContrib 调试 ModelStateToTempDataAttribute,认为这是他们导入/导出模型状态的代码中的错误。

感谢您的帮助!

编辑 - 添加重现代码

按照以下步骤重现:

  1. 启动项目。 Property1 应为空白(必需),Property2 应具有“abc”
  2. 将 Property2 更改为“xxx”
  3. 提交表单(注意 ClientValidationEnabled 为 False)
  4. 表单已发布、重定向、加载 (PRG)。 Property2 文本框有“xxx”,您将在 DisplayFor 的正下方看到“abc”。

控制器

[ModelStateToTempData] //From MVCContrib
public class HomeController : Controller
{

    [HttpGet]
    public ActionResult Index()
    {
        //simulate load from db
        var model = new FormModel() { MyProperty2 = "abc" }; 

        return View(model);
    }

    [HttpGet]
    public ActionResult Success()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Index(FormModel model)
    {
        if (ModelState.IsValid)
        {
            return RedirectToAction("Success");
        }
        else
        {
            return RedirectToAction("Index");
        }
    }
}

型号

public class FormModel
{
  [Required]
  public string MyProperty1 { get; set; }

  public string MyProperty2 { get; set; }
}

查看

@model MvcApplication4.Models.FormModel
@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>FormModel</legend>

    <div class="editor-label">
        @Html.LabelFor(model => model.MyProperty1)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.MyProperty1)
        @Html.ValidationMessageFor(model => model.MyProperty1)
    </div>

    <div class="editor-label">
        @Html.LabelFor(model => model.MyProperty2)
    </div>
    <div class="editor-field">
        @Html.EditorFor(model => model.MyProperty2)
        @Html.ValidationMessageFor(model => model.MyProperty2)
    </div>

    @Html.DisplayFor(model => model.MyProperty2)

    <p>
        <input type="submit" value="Save" />
    </p>
</fieldset>
}

配置:

<add key="ClientValidationEnabled" value="false" />

ModelStateToTempData (MVCContrib):

public class ModelStateToTempDataAttribute : ActionFilterAttribute
    {
        public const string TempDataKey = "__MvcContrib_ValidationFailures__";

        /// <summary>
        /// When a RedirectToRouteResult is returned from an action, anything in the ViewData.ModelState dictionary will be copied into TempData.
        /// When a ViewResultBase is returned from an action, any ModelState entries that were previously copied to TempData will be copied back to the ModelState dictionary.
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var modelState = filterContext.Controller.ViewData.ModelState;

            var controller = filterContext.Controller;

            if(filterContext.Result is ViewResultBase)
            {
                //If there are failures in tempdata, copy them to the modelstate
                CopyTempDataToModelState(controller.ViewData.ModelState, controller.TempData);
                return;
            }

            //If we're redirecting and there are errors, put them in tempdata instead (so they can later be copied back to modelstate)
            if((filterContext.Result is RedirectToRouteResult || filterContext.Result is RedirectResult) && !modelState.IsValid)
            {
                CopyModelStateToTempData(controller.ViewData.ModelState, controller.TempData);
            }
        }

        private void CopyTempDataToModelState(ModelStateDictionary modelState, TempDataDictionary tempData)
        {
            if(!tempData.ContainsKey(TempDataKey)) return;

            var fromTempData = tempData[TempDataKey] as ModelStateDictionary;
            if(fromTempData == null) return;

            foreach(var pair in fromTempData)
            {
                if (modelState.ContainsKey(pair.Key))
                {
                    modelState[pair.Key].Value = pair.Value.Value;

                    foreach(var error in pair.Value.Errors)
                    {
                        modelState[pair.Key].Errors.Add(error);
                    }
                }
                else
                {
                    modelState.Add(pair.Key, pair.Value);
                }
            }
        }

        private static void CopyModelStateToTempData(ModelStateDictionary modelState, TempDataDictionary tempData)
        {
            tempData[TempDataKey] = modelState;
        }
    }

【问题讨论】:

  • DisplayFor 是正确的方法。检查您的 QueryString 以查看是否有设置为 SelectedTags 的值,我敢肯定`首先显示在实际模型值之上。
  • @BuildStarted 没有查询字符串。我有一个包含 EditorFor 和 DisplayFor 的测试页面,只有 EditorFor 显示发布的值。
  • 您能否发布您的代码(查看模型、操作方法和视图)? DisplayFor 应该可以胜任。
  • @BuildStarted 代码添加

标签: asp.net-mvc asp.net-mvc-3


【解决方案1】:

您可以从 modelstate 字典中读取这些值,例如

<%:Html.ViewData.ModelState["key"] %>

但是,在我看来,SelectedTags 是在您调用 EditorFor(model=&gt;model.SelectedTags) 时显示以供编辑的对象的枚举。在这种情况下,您极不可能通过调用Html.ViewData.ModelState["SelectedTags"] 得到任何东西。您将不得不迭代 ModelState 字典中的键,并检查键是否以 SelectedTags 前缀开头,然后您可以相应地读取其值。

【讨论】:

  • 不是枚举,是字符串。嗯,这是唯一的方法吗?似乎应该有一个像编辑器/输入一样工作的内置帮助器
  • 如果您可以发布您的帖子操作结果和编辑器模板,我们将能够更好地提供帮助
  • 这是我找到的最接近的,但会留下一些问题,希望有人会发布具有此逻辑的内置 HtmlHelper(最好是强类型)。
  • 其实,现在我已经尝试过了,是的,我可以取出数据,但是如果模型状态未设置,它将为空(现在看起来很明显)。因此它不会重现与输入助手中相同的行为,因为输入助手检查的源不是模型状态
  • 另外的来源是传递给视图的模型对象
【解决方案2】:

在您的视图 -> 共享 -> 显示模板中,创建 SelectedTags.cshtml

这将是您的显示模板。里面写点东西就行了

@model YourProject.WebUI.Models.SelectedTags

@for(int i = 0; i < Model.Tags.Count(); i++){
   // Assuming that selected tags contains a list of tags.
   // Replace <p> with whatever feels suitable
   <p>Model.Tags[i]</p>
}

然后您可以在视图中使用此显示模板:

@Html.DisplayFor(model => model.SelectedTags,"SelectedTags") 

这也应该有效:

@Html.DisplayFor(model => model.SelectedTags) 

【讨论】: