7

次の設定を検討してください。

モデル:

public class Product
{
    [ReadOnly(true)]
    public int ProductID
    {
        get;
        set;
    }

    public string Name
    {
        get;
        set;
    }
}

意見:

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" 
Inherits="System.Web.Mvc.ViewPage<MvcApplication4.Models.Product>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <%= Html.EditorForModel() %>
</asp:Content>

コントローラ:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new Product
            {
                ProductID = 1,
                Name = "Banana"
            });
    }
}

結果は次のとおりです。 代替テキスト

ProductID属性を介してプロパティを編集できないと予想していましたReadOnly(true)。これはサポートされていますか? そうでない場合、モデルの一部のプロパティが読み取り専用であることを ASP.NET MVC に示唆する方法はありますか? ProductID経由で非表示にしたくありません[ScaffoldColumn(false)]

4

3 に答える 3

11

「 ReadOnly 」のクラスのプロパティに UIHintAttribute を追加することで、この問題を解決しました。

[UIHint("ReadOnly")]
public int ClassID { get; set; }

次に、これを含む~\Views\Shared\EditorTemplates\ReadOnly.ascxファイルをプロジェクトに追加しました。

<%= Model %>

カスタム テンプレートを追加する非常に簡単な方法で、書式設定などを含めることができます。

于 2011-02-25T02:52:58.443 に答える
9

および属性は、メタデータ プロバイダーによって消費されますがReadOnlyRequired使用されません。で入力を取り除きたい場合EditorForModelは、カスタム テンプレートまたは[ScaffoldColumn(false)].

カスタム テンプレートの場合~/Views/Home/EditorTemplates/Product.ascx:

<%@ Control Language="C#" Inherits="ViewUserControl<Product>" %>

<%: Html.LabelFor(x => x.ProductID) %>
<%: Html.TextBoxFor(x => x.ProductID, new { @readonly = "readonly" }) %>

<%: Html.LabelFor(x => x.Name) %>
<%: Html.TextBoxFor(x => x.Name) %>

また、デフォルトのモデル バインダーは、値をプロパティにコピーしないことに注意してください[ReadOnly(false)]。この属性は、既定のテンプレートによってレンダリングされる UI には影響しません。

于 2010-08-18T10:45:51.643 に答える
2
<%@ Control Language="C#" Inherits="ViewUserControl<Product>" %>

<%: Html.LabelFor(x => x.ProductID) %>
<%: Html.TextBoxFor(x => x.ProductID, new { @readonly = true }) %>

<%: Html.LabelFor(x => x.Name) %>
<%: Html.TextBoxFor(x => x.Name) %>
于 2012-02-08T01:47:14.627 に答える