【问题标题】:MVC 3 edit view for certain fields only仅针对某些字段的 MVC 3 编辑视图
【发布时间】:2017-03-15 13:38:23
【问题描述】:

我有这个模型:

public class ExchangeRate
{
    [Key]
    public  int ExchangeRateID { get; set; }
    [Required]
    [Display(Name = "Currency:")]
    public  string Currency { get; set; }
    [Required]
    public  decimal Rate { get; set; }
}

“创建”视图工作正常,但是当我在编辑视图中时,我只希望显示货币属性,而不是可编辑的。我该怎么做?如果我为这个类创建另一个“仅查看”模型,那么我将省略“货币”属性并且无法显示它。

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
    <legend>ExchangeRate</legend>

    @Html.HiddenFor(model => model.ExchangeRateID)

    <div class="editor-label">
        @Html.LabelFor(model => model.Currency)
    </div>
    <div class="editor-field">
         @Html.DisplayFor(model => model.Currency)
    </div>

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

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

}

将@Html.EditorFor(model => model.Currency) 更改为@Html.DisplayFor(model => model.Currency) 不起作用,因为模型状态在回发到控制器时变得无效。

【问题讨论】:

    标签: asp.net-mvc-3


    【解决方案1】:

    你可以添加

    @Html.HiddenFor(model => model.Currency)
    

    在您的表单中,然后使用

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

    显示货币属性的只读值。这样,当您发布时,值将在发布的模型中一起发送。

    【讨论】:

    • 这也可以与 Twitter 引导程序结合使用,例如在视图中使用以下内容:&lt;span class="uneditable-input"&gt;@Html.DisplayFor(m =&gt; m.ProductName)&lt;/span&gt;
    【解决方案2】:

    您正在寻找:

    [HiddenInput(DisplayValue=true)]
    

    然后显示编辑器,而不是显示(使用EditorFor)。

    这会以只读方式显示值,但会添加一个隐藏输入,以便发布的状态有效。

    【讨论】:

    • 用 MVC 4 试过这个,但对我不起作用,导致只隐藏。 EditorFor() 不显示任何内容。不过,我可能忽略了一些东西。我选择了对我有用的@mreyeros 解决方案。
    【解决方案3】:

    显示货币但不编辑尝试

    @Html.Label("Currency", Model.Currency)
    

    如果您还需要将货币值发送回控制器,请尝试

    @Html.HiddenFor(m => m.Currency)
    

    我希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 2021-02-16
      • 1970-01-01
      • 1970-01-01
      • 2011-02-21
      • 2012-01-06
      • 1970-01-01
      相关资源
      最近更新 更多