.net 使用Razor语法将模型绑定到DropDownList
好的,我使用以下Razor语法创建此视图:.net 使用Razor语法将模型绑定到DropDownList,.net,asp.net-mvc,api,razor,.net,Asp.net Mvc,Api,Razor,好的,我使用以下Razor语法创建此视图: @model DoggrOPI.Models.WellSearch <div class="container-fluid"> <h2>Well Search</h2> @for (int i = 0; i < Model.Counties.Count; i++) { @Html.DisplayFor(m => m.Counties[i].CountyName
@model DoggrOPI.Models.WellSearch
<div class="container-fluid">
<h2>Well Search</h2>
@for (int i = 0; i < Model.Counties.Count; i++)
{
@Html.DisplayFor(m => m.Counties[i].CountyName)
}
</div>
这正是我想要的,但我无法将其绑定到@Html.DropDownListFor。这样做的正确语法是什么
我的模型是这样的:
public partial class CountyInfo
{
public string CountyName { get; set; }
}
型号:
public class WellSearch
{
public int CountyId { get; set; }
public IEnumerable<CountyInfo> Counties { get; set; }
}
public partial class CountyInfo
{
public int CountyId {get; set;}
public string CountyName { get; set; }
}
基本上,在主视图模型中添加一个
CountyId
,当您将表单发送到服务器时,它将与您选择的下拉选项相匹配。您希望将所选值绑定到什么属性?您能给我一个例子,告诉我哪个属性吗。我只需要任何东西,什么都不能用。@Html.DropDownListFor(m=>m.MyProperty,new SelectList(Model.Countries,“CountryID”,“CountryName”)
将为国家/地区的每个项目创建选项,其中选项的值为CountryID
,选项的显示文本为CountryName
。发布表单时,所选选项的值将绑定到propertyMyProperty
。收到以下错误:说明:发生错误编译服务此请求所需的资源时出现红色。请查看以下特定错误详细信息,并适当修改源代码。编译器错误消息:CS1061:“DoggrOPI.Models.WellSearch”不包含“MyProperty”的定义,并且没有扩展方法“MyProperty”接受类型的第一个参数可以找到e'DoggrOPI.Models.WellSearch'(您是否缺少using指令或程序集引用?)源错误:我给了您一个示例(您没有为WellSearch
或国家/地区发布您的模型)。只需将MyProperty
替换为WellSearch
中要绑定的属性的名称即可。
public class WellSearch
{
public int CountyId { get; set; }
public IEnumerable<CountyInfo> Counties { get; set; }
}
public partial class CountyInfo
{
public int CountyId {get; set;}
public string CountyName { get; set; }
}
@Html.DropDownListFor(m => m.CountyId , new SelectList(Model.Counties), "CountyId", "CountyName "))