C# Post表单在模型中获取空值
当我提交表单时,我的课程列表进入我的ViewModel时会得到空值。 这是我的ViewModel:C# Post表单在模型中获取空值,c#,asp.net-mvc-3,razor,viewmodel,C#,Asp.net Mvc 3,Razor,Viewmodel,当我提交表单时,我的课程列表进入我的ViewModel时会得到空值。 这是我的ViewModel: public class CandidateViewModel { public string Name { get; set; } public IList<CourseViewModel> Courses { get; set; } public CandidateViewModel() { Name = "Kiwanax";
public class CandidateViewModel
{
public string Name { get; set; }
public IList<CourseViewModel> Courses { get; set; }
public CandidateViewModel()
{
Name = "Kiwanax";
Courses = new List<CourseViewModel>();
for (int count = 0; count < 5; ++count)
{
Courses.Add(new CourseViewModel(
string.Format("Course_{0}", count), 5));
}
}
}
public class CourseViewModel
{
public long ID { get; set; }
public string Name { get; set; }
public OptionViewModel SelectedOption { get; set; }
public IList<OptionViewModel> Options { get; set; }
public CourseViewModel(string name, int numberOfOptions)
{
Name = name;
Options = new List<OptionViewModel>();
for (int count = 1; count <= numberOfOptions; ++count)
{
Options.Add(new OptionViewModel(count.ToString(),
string.Format("Option {0}", count)));
}
SelectedOption = Options[0];
}
}
public class OptionViewModel
{
public string Value { get; set; }
public string Description { get; set; }
}
公共类候选视图模型
{
公共字符串名称{get;set;}
公共IList课程{get;set;}
公共候选视图模型()
{
Name=“Kiwanax”;
课程=新列表();
用于(整数计数=0;计数<5;++计数)
{
添加(新的CourseView模型(
格式(“Course_{0}”,count),5);
}
}
}
公共课课件模型
{
公共长ID{get;set;}
公共字符串名称{get;set;}
公共选项ViewModel SelectedOption{get;set;}
公共IList选项{get;set;}
public CourseView模型(字符串名称,整数选项)
{
名称=名称;
选项=新列表();
对于(int count=1;count i.Courses[count]。选择选项,
新建选择列表(Model.Courses[count]。选项,“值”、“说明”,Model.Courses[count]。SelectedOption))
@Html.HiddenFor(i=>i.Courses[count].ID)
@Model.Courses[count].Name
}
但是,当我从表单发布时,我从IList获取空值。您不能将下拉列表绑定到复杂的属性值:
i => i.Courses[count].SelectedOption
它必须绑定到将发送到服务器的相应基元类型:
i => i.Courses[count].SelectedOption.Value
请记住,在HTML中,
元素仅将所选值作为简单字符串类型发送到服务器。此ID来自@HTML.HiddenFor(i=>i.Courses[count].ID)中的何处?我在CourseViewModel中放入了一个名为ID的属性。但是,对不起,忘了在这里写入。这个CursorDisponiveis对象是什么?你能显示更多的代码吗?很难说是怎么回事?现在我修复了我的错误。我在主题的最后说:当我从我的表单发布时,IList命名的Courses会得到空值。所有属性都是nu那是我的问题。问题在这里@Html.DropDownListFor(i=>i.Courses[count].SelectedOption,
lambda的右侧不应该是复杂类型谢谢,Darin,它解决了我的一个问题!现在,检查一下:当我将trhu Javascript任意内容更改为这个生成的selects元素时,我会得到null。例如:当我删除一些选项trhu JS时,我会在post上得到null!比如:$(“courses li select”).each(function(){if($(this.val()==-1)$(this.attr('disabled','disabled');})如果禁用或删除列表中的某些下拉列表,则索引中会出现漏洞,并且默认模型绑定器无法正确绑定值。请阅读以下博文,了解绑定到集合的工作原理:。因此,您有两种可能性=>1。修复其他select元素的索引(可能很难实现)2.如前一篇博文末尾所述,在元素名称中使用非顺序索引-在这种情况下,您将不关心删除元素。另外,请确保您已阅读以下文章,了解自定义Html.BeginCollectionItem帮助器的示例实现,该帮助器允许您生成非顺序索引:
i => i.Courses[count].SelectedOption.Value