Asp.Net Html.editorFor外部ID从其他表转换为名称

时间:2018-11-02 13:54:26

标签: c# html asp.net-mvc

 <div class="form-group">
    @Html.LabelFor(model => Model.countyid, new {@class = "control-label"})
    @Html.EditorFor(model => Model.countyid, new {htmlAttributes = new {@class = "form-control"}})
    @Html.ValidationMessageFor(model => model.countyid)
</div>

我的主表有一个与该县表链接的县名外键。上面是我的县名编辑。

问题-我需要将ID转换为另一张表中的名称列表,以便不向用户显示这些ID号。如果我可以在理论上有所帮助,或者从类似问题中获得一个例子,将不胜感激。谢谢

编辑:详细信息-我的第一个表还有其他数据,但外键是County ID。县表具有ID和名称,我需要将名称提取为我用于第一个表的相同格式,以替换ID,然后从所选名称中发回ID。

型号:县

public partial class County
{
    public int id { get; set; }
    public int countryid { get; set; }
    public bool deleted { get; set; }
    public string name { get; set; }
}

公司:

public partial class Agency
{
    public int id { get; set; }
    public bool deleted { get; set; }
    public string name { get; set; }
    public string address1 { get; set; }
    public string address2 { get; set; }
    public string address3 { get; set; }
    public string town { get; set; }
    public int countyid { get; set; }
    public string postcode { get; set; }
    public string telephoneno { get; set; }
    public string companyno { get; set; }
}

1 个答案:

答案 0 :(得分:0)

您的模型中不仅应包含ID:

 public class CountyInfo{
        public int countyid {get;set;}
        public string CountyName{get;set;}
        //Whatever other properties you want in the model to use on the page
}

由于您说了一个ID列表,所以我假设您想一次从这样的数据库模型中提取多个记录,并将从表中获得的内容映射到它:

public class CountyInfoList{
        public List<CountyInfo> Counties {get;set;}
        //other props that go to counties in general
}

然后您可以将其添加到您的主模型

public class PrimaryTableModel {
       public int PrimaryTableID {get;set;}
       //if there's a one to one relationship between primary table and county
       public CountyInfo County {get;set;}
       //or if there's a many to one relationship 
       public CountyInfoList CountiesList {get;set;}
 }

我认为您不是要在编辑器中使用Id字段。如果这是您要编辑的对象,请在上方隐藏ID。应该是这样的:

@Html.HiddenFor(model=>model.countyid)
@Html.EditorFor(model => Model.CountyName, new {htmlAttributes = new {@class = "form-control"}})

或者如果使用主表模型

@Html.HiddenFor(model=>model.County.countyid)
@Html.EditorFor(model => Model.County.CountyName, new {htmlAttributes = new {@class = "form-control"}})

 @foreach (var c in Model.CountiesList.Counties )
        {
@Html.HiddenFor(model=>c.countyid)
@Html.EditorFor(model => c.CountyName, new {htmlAttributes = new {@class = "form-control"}})