asp.net-mvc - Html Helper 从模型状态获取值

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

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”。

Controller

[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" />

模型状态到临时数据(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;
        }
    }

最佳答案

您可以从模型状态字典中读取这些值,例如

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

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

关于asp.net-mvc - Html Helper 从模型状态获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7735179/

相关文章:

c# - Mac OS X 上的 ASP.NET MVC 5

c# - 充分利用具有 n(3) 层架构的 MVC Owin 标识

c# - 在 MVC 项目中的何处创建数据访问层

asp.net-mvc - MVC - 使用 Windows 身份验证并注入(inject)角色而不按请求执行

c# - WCF 数据服务集合加载

asp.net-mvc - 如何检查MVC View 中的空值?

multithreading - asp.net mvc 3应用程序需要写一行,然后等待该行被更新,然后再更新UI

asp.net-mvc-3 - 在模型中包含 SampleData.cs 后尝试运行 MVC Music Store 时出现异常

asp.net-mvc-3 - 如何减少对 Controller 的注入(inject)依赖项的数量

c# - MVC 重定向到默认路由