我是MVC.Net和razorviews的新手。 我有一个包含卡片列表的模型。我想在我的视图中的下拉框中显示此列表。但我不被允许。从一个例子中,我发现了这个代码并尝试了一下:
列表的类:
public class CardType
{
public CardType(string cardTypeName)
{
this.CardTypeName = cardTypeName;
}
public string CardTypeName { get; set; }
}
型号:
public class MyCardsViewModel
{
public IEnumerable<PaymentCard> PaymentCards { get; set; }
public AddPaymentcard PaymentCardInformation { get; set; }
}
public class AddPaymentcard
{
public string CardTypeName { get; set; }
public IEnumerable<SelectListItem> CardTypeList
{
get
{
return _cardTypes.Select(x => new SelectListItem {Value = x.CardTypeName, Text = x.CardTypeName}).ToList();
}
}
public List<CardType> _cardTypes;
}
控制器的方法:
// GET: /MyCards/
public ActionResult Index()
{
string userId = User.Identity.GetUserId();
MyCardsViewModel viewModel = new MyCardsViewModel();
var user = _userRepository.GetUser(userId);
viewModel.PaymentCards = user.PaymentCards; //Don't mind this, it is something else :)
var cardTypeList = _cardTypeRepository.GetCardTypes();
viewModel.PaymentCardInformation=new AddPaymentcard
{
_cardTypes = cardTypeList
};
return View(viewModel);
}
//Get: MyCards/AddPaymentcard
public ActionResult AddPaymentcard()
{
return View();
}
查看:
引入MyCardsViewModel的索引视图并添加部分视图AddPaymentcard.cshtml:
@model Kvittering.TaxiFinans.Web.Models.MyCardsViewModel
(...)
@Html.Partial("~/Views/MyCards/AddPaymentcard.cshtml", @Model.PaymentCardInformation );
AddPaymentcard视图:
@model Kvittering.TaxiFinans.Web.Models.AddPaymentcard
(...)
<div class="form-group">
@Html.LabelFor(m => m.CardTypeName, new { @class = "control-label col-md-2"})
<div class="col-md-offset-2 col-md-8">
@Html.DropDownListFor(m => m.CardTypeName, @Model.CardTypeList)
</div>
</div>
任何人都可以帮我吗? :/
答案 0 :(得分:1)
解决方案可以是Select
new SelectListItem
,这样您就可以停止使用硬编码字符串,并确保获得所需内容。
public class AddPaymentcard
{
public string CardTypeName { get; set; }
public IEnumerable<SelectListItem> CardTypeList
{
get { return _cardTypes.Select(x => new SelectListItem { Value = x.CardTypeName, Text = x.CardTypeName }); }
}
public List<CardType> _cardTypes;
}
如果您的视图模型类型为MyCardsViewModel
@Html.DropDownListFor(m => m.PaymentCardInformation.CardTypeName, @Model.PaymentCardInformation.CardTypeList)