18

我对 ASP.net MVC 世界还很陌生,我试图弄清楚如何呈现一组强类型为视图模型的复选框。在网络表单中,我只会使用复选框列表控件,但我对 MVC 有点迷失。

我正在为婚礼策划业务构建一个简单的联系表格,并且需要将用户选择的任何复选框值传递给我的控制器。

表单复选框需要如下所示: 在此处输入图像描述

您的帮助将不胜感激。谢谢!

这是我到目前为止所拥有的。

控制器

[HttpPost]
public ActionResult Contact(ContactViewModel ContactVM)
{
    if (!ModelState.IsValid)
    {
        return View(ContactVM);
    }
    else
    {
        //Send email logic

        return RedirectToAction("ContactConfirm");
    }
}

查看模型

public class ContactViewModel
{
    [Required]
    public string Name { get; set; }

    [Required]
    public string Phone { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [Required]
    public string Subject { get; set; }
    public IEnumerable<SelectListItem> SubjectValues
    {
        get
        {
            return new[]
            {
                new SelectListItem { Value = "General Inquiry", Text = "General Inquiry" },
                new SelectListItem { Value = "Full Wedding Package", Text = "Full Wedding Package" },
                new SelectListItem { Value = "Day of Wedding", Text = "Day of Wedding" },
                new SelectListItem { Value = "Hourly Consultation", Text = "Hourly Consultation" }  
            };
        }
    }


    //Not sure what I should do for checkboxes...

}

看法

@model NBP.ViewModels.ContactViewModel

@{
    ViewBag.Title = "Contact";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

@using (Html.BeginForm())
{
    <div id="ContactContainer">
        <div><span class="RequiredField">*&nbsp;</span>Your Name:</div>
        <div>
            @Html.TextBoxFor(model => model.Name)
        </div>
        <div><span class="RequiredField">*&nbsp;</span>Your Phone:</div>
        <div>
            @Html.TextBoxFor(model => model.Phone)
        </div>
        <div><span class="RequiredField">*&nbsp;</span>Your Email:</div>
        <div>
            @Html.TextBoxFor(model => model.Email)
        </div>
        <div>Subject:</div>
        <div> 
            @Html.DropDownListFor(model => model.Subject, Model.SubjectValues)
        </div>
        <div>Vendor Assistance:</div>
        <div>

            <!-- CHECKBOXES HERE -->

        </div>
        <div>
            <input id="btnSubmit" type="submit" value="Submit" />
        </div>
    </div>
}
4

3 回答 3

20

您可以丰富您的视图模型:

public class VendorAssistanceViewModel
{
    public string Name { get; set; }
    public bool Checked { get; set; }
}

public class ContactViewModel
{
    public ContactViewModel()
    {
        VendorAssistances = new[]
        {
            new VendorAssistanceViewModel { Name = "DJ/BAND" },
            new VendorAssistanceViewModel { Name = "Officiant" },
            new VendorAssistanceViewModel { Name = "Florist" },
            new VendorAssistanceViewModel { Name = "Photographer" },
            new VendorAssistanceViewModel { Name = "Videographer" },
            new VendorAssistanceViewModel { Name = "Transportation" },
        }.ToList();
    }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Phone { get; set; }

    [Required]
    [DataType(DataType.EmailAddress)]
    public string Email { get; set; }

    [Required]
    public string Subject { get; set; }
    public IEnumerable<SelectListItem> SubjectValues
    {
        get
        {
            return new[]
            {
                new SelectListItem { Value = "General Inquiry", Text = "General Inquiry" },
                new SelectListItem { Value = "Full Wedding Package", Text = "Full Wedding Package" },
                new SelectListItem { Value = "Day of Wedding", Text = "Day of Wedding" },
                new SelectListItem { Value = "Hourly Consultation", Text = "Hourly Consultation" }  
            };
        }
    }

    public IList<VendorAssistanceViewModel> VendorAssistances { get; set; }
}

控制器:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new ContactViewModel());
    }

    [HttpPost]
    public ActionResult Index(ContactViewModel model)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        //Send email logic
        return RedirectToAction("ContactConfirm");
    }
}

看法:

@using (Html.BeginForm())
{
    <div id="ContactContainer">
        <div><span class="RequiredField">*&nbsp;</span>Your Name:</div>
        <div>
            @Html.TextBoxFor(model => model.Name)
        </div>
        <div><span class="RequiredField">*&nbsp;</span>Your Phone:</div>
        <div>
            @Html.TextBoxFor(model => model.Phone)
        </div>
        <div><span class="RequiredField">*&nbsp;</span>Your Email:</div>
        <div>
            @Html.TextBoxFor(model => model.Email)
        </div>
        <div>Subject:</div>
        <div> 
            @Html.DropDownListFor(model => model.Subject, Model.SubjectValues)
        </div>
        <div>Vendor Assistance:</div>
        <div>
            @for (int i = 0; i < Model.VendorAssistances.Count; i++)
            {
                <div>
                    @Html.HiddenFor(x => x.VendorAssistances[i].Name)
                    @Html.CheckBoxFor(x => x.VendorAssistances[i].Checked)
                    @Html.LabelFor(x => x.VendorAssistances[i].Checked, Model.VendorAssistances[i].Name)
                </div>
            }
        </div>
        <div>
            <input id="btnSubmit" type="submit" value="Submit" />
        </div>
    </div>
}
于 2012-10-10T07:25:48.283 回答
3

在视图模型中使用字符串数组。然后你可以使用我一起破解的助手。如果您不想使用帮助程序和枚举,请查看底部的实际 Html。活页夹将返回一个字符串数组,其中仅包含选定的字符串值。如果没有选择它,它会为您的数组返回一个空值。你必须考虑到这一点,你已经被警告了:)

查看型号:

[Display(Name = "Which Credit Cards are Accepted:")]
        public string[] CreditCards { get; set; }

帮手:

public static HtmlString CheckboxGroup<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> propertySelector, Type EnumType)
        {
            var groupName = GetPropertyName(propertySelector);
            var modelValues = ModelMetadata.FromLambdaExpression(propertySelector, htmlHelper.ViewData).Model;//propertySelector.Compile().Invoke(htmlHelper.ViewData.Model);
        StringBuilder literal = new StringBuilder();  

        foreach (var value in Enum.GetValues(EnumType))
        {
            var svalue = value.ToString();
            var builder = new TagBuilder("input");
            builder.GenerateId(groupName);
            builder.Attributes.Add("type", "checkbox");
            builder.Attributes.Add("name", groupName);
            builder.Attributes.Add("value", svalue);
            var contextValues = HttpContext.Current.Request.Form.GetValues(groupName);
            if ((contextValues != null && contextValues.Contains(svalue)) || (modelValues != null && modelValues.ToString().Contains(svalue)))
            {
                builder.Attributes.Add("checked", null);
            }

            literal.Append(String.Format("</br>{1}&nbsp;<span>{0}</span>", svalue.Replace('_', ' '),builder.ToString(TagRenderMode.Normal)));
        }

        return (HtmlString)htmlHelper.Raw(literal.ToString()); 
    }

    private static string GetPropertyName<T, TProperty>(Expression<Func<T, TProperty>> propertySelector)
    {
        var body = propertySelector.Body.ToString();
        var firstIndex = body.IndexOf('.') + 1;
        return body.Substring(firstIndex);
    }

HTML:

@Html.CheckboxGroup(m => m.CreditCards, typeof(VendorCertification.Enums.CreditCardTypes))

如果辅助扩展吓到您,请使用它:

            <input id="CreditCards" name="CreditCards" type="checkbox" value="Visa" 
            @(Model.CreditCards != null && Model.CreditCards.Contains("Visa") ? "checked=true" : string.Empty)/>
            &nbsp;<span>Visa</span><br />

            <input id="CreditCards" name="CreditCards" type="checkbox" value="MasterCard" 
            @(Model.CreditCards != null && Model.CreditCards.Contains("MasterCard") ? "checked=true" : string.Empty)/>
            &nbsp;<span>MasterCard</span><br />
于 2016-06-17T22:07:07.210 回答
-2

对我来说这也有效,我认为这是最简单的(阅读以前的答案)。

视图模型有一个用于复选框的字符串 []。

    public string[] Set { get; set; }

该视图具有此代码,您可以根据需要多次重复输入。输入控件的名称、ID 必须与视图模型的属性名称相匹配。

<div class="col-md-3">
  <div class="panel panel-default panel-srcbox">
    <div class="panel-heading">
      <h3 class="panel-title">Set</h3>
    </div>
    <div class="panel-body">
      <div class="form-group-sm">
        <label class="control-label col-xs-3">1</label>
        <div class="col-sm-8">
          <input type="checkbox" id="Set" name="Set" value="1" />
        </div>
        <label class="control-label col-xs-3">2</label>
        <div class="col-sm-8">
          <input type="checkbox" id="Set" name="Set" value="2" />
        </div>
      </div>
    </div>
  </div>
</div>

在 post 方法中,Set 变量是一个数组,具有已检查的值。

于 2017-05-22T11:49:26.007 回答