How can I make Html.CheckBoxFor() work on a string field?

前端 未结 4 1020
你的背包
你的背包 2021-01-02 02:15

I\'m using ASP.NET MVC3 with Razor and C#. I am making a form builder of sorts, so I have a model that has a collection of the following object:

public class         


        
4条回答
  •  执念已碎
    2021-01-02 02:56

    You could also add a property on your viewmodel:

        public class MyFormField
        {
            public string Name { get; set; }
            public string Value { get; set; }
    
            public bool CheckBoxValue
            {
                get { return Boolean.Parse(Value); }
            }
    
            public MyFormType Type { get; set; }
        }
    

    Your view would be something like this:

    @model MyFormField
    @{
        switch (Model.Type)
        {
            case MyFormType.Textbox:
                @Html.TextBoxFor(m => m.Value)
            case MyFormType.Checkbox:
                @Html.CheckBoxFor(m => m.CheckBoxValue)  // This does work!
        }
    }
    

    Use Boolean.TryParse if you want to avoid exceptions.

提交回复
热议问题