Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ssis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
ASP.NET MVC3模型绑定问题-将下拉列表的值获取到模型中?_Asp.net_Asp.net Mvc 3 - Fatal编程技术网

ASP.NET MVC3模型绑定问题-将下拉列表的值获取到模型中?

ASP.NET MVC3模型绑定问题-将下拉列表的值获取到模型中?,asp.net,asp.net-mvc-3,Asp.net,Asp.net Mvc 3,为了解决这个问题,我掉了更多的头发,所以我真的希望你能帮我 我有一个Telerik MVC网格: 我有一个地址的自定义编辑器模板(Address.ascx) 我的ImporterDetails模型: public class ImporterViewModel : IEnumerableViewModel { public int ImporterId { get; set; } [Required] [DisplayName(

为了解决这个问题,我掉了更多的头发,所以我真的希望你能帮我

我有一个Telerik MVC网格:

我有一个地址的自定义编辑器模板(Address.ascx)

我的ImporterDetails模型:

   public class ImporterViewModel : IEnumerableViewModel
    {
        public int ImporterId { get; set; }

        [Required]
        [DisplayName("Importer Name *")]
        public string ImporterName { get; set; }

        [Required]
        [DisplayName("Importer Address *")]
        public Address ImporterAddress { get; set; }

        public static ImporterViewModel CreateImporter()
        {
            return new ImporterViewModel
                       {
                           ImporterName = Guid.NewGuid().ToString().Substring(0, 5),
                           ImporterAddress = Address.CreateDummyAddress(),
                       };
        }

    }
以及AddressViewModel:

[Bind(Exclude = "State, Country")]
public class Address
{
    public int AddressId { get; set; }

    [DisplayName("Address Line 1")]
    [Required]
    public string Line1 { get; set; }

    [DisplayName("Address Line 2")]
    public string Line2 { get; set; }

    [DisplayName("Postcode")]
    [Required]
    [RegularExpression(RegexConstants.AUSTRALIAN_POSTCODE_PATTERN, ErrorMessage = "Invalid post code")]
    public string Postcode { get; set; }

    [DisplayName("State")]
    public State State { get; set; }

    [DisplayName("Suburb")]
    public string Suburb { get; set; }

    [DisplayName("Country")]
    public Country Country { get; set; }

    [Required]
    public int CountryId { get; set; }

    [Required]
    public int StateId { get; set; }

    /// <summary>
    /// Creates a new dummy instance of Address
    /// </summary>
    /// <returns></returns>
    public static Address CreateDummyAddress()
    {
        return new Address
                   {
                       Country = ServiceLocatorFactory.GetCodeServiceLocator<Country>().Get(x => x.CodeValue.ToLower() == "canada"),
                       State = ServiceLocatorFactory.GetCodeServiceLocator<State>().Get(x => x.CodeValue.ToLower() == "nsw"),
                       Line1 = Guid.NewGuid().ToString().Substring(0, 15),
                       Line2 = Guid.NewGuid().ToString().Substring(0, 15),
                       Suburb = "Dandenong",
                       Postcode = "2606",
                   };
    }

    public string AddressStrings
    {
        get
        {
            return ToString();
        }
    }

    public override string ToString()
    {
        // create a blank StringBuilder
        var sb = new StringBuilder();

        // add the first address line
        sb.Append(string.Format("{0}, ", Line1));

        // add the second address line
        sb.Append(string.Format("{0}, ", Line2));

        sb.Append(string.Format("{0}, ", Suburb));
        sb.Append(string.Format("{0} {1}, ", State == null ? string.Empty : State.Description, Postcode));
        sb.Append(string.Format("{0}", Country == null ? string.Empty : Country.Description));

        // and then return it as a single (formatted) string
        return sb.ToString();
    }
}
[Bind(Exclude=“State,Country”)]
公共课堂演讲
{
public int AddressId{get;set;}
[显示名称(“地址行1”)]
[必需]
公共字符串Line1{get;set;}
[显示名称(“地址行2”)]
公共字符串第2行{get;set;}
[显示名称(“邮政编码”)]
[必需]
[RegularExpression(RegexConstants.AUSTRALIAN_POSTCODE_PATTERN,ErrorMessage=“无效邮政编码”)]
公共字符串邮政编码{get;set;}
[显示名称(“状态”)]
公共状态状态{get;set;}
[显示名称(“郊区”)]
公共字符串{get;set;}
[显示名称(“国家”)]
公共国家{get;set;}
[必需]
public int CountryId{get;set;}
[必需]
public int StateId{get;set;}
/// 
///创建地址的新虚拟实例
/// 
/// 
公共静态地址CreateDummyAddress()
{
返回新地址
{
Country=ServiceLocatorFactory.GetCodeServiceLocator().Get(x=>x.CodeValue.ToLower()==“加拿大”),
State=ServiceLocatorFactory.GetCodeServiceLocator().Get(x=>x.CodeValue.ToLower()==“nsw”),
Line1=Guid.NewGuid().ToString().Substring(0,15),
Line2=Guid.NewGuid().ToString().Substring(0,15),
郊区=“丹德农”,
邮政编码=“2606”,
};
}
公共字符串地址字符串
{
得到
{
返回到字符串();
}
}
公共重写字符串ToString()
{
//创建一个空白的StringBuilder
var sb=新的StringBuilder();
//添加第一个地址行
sb.Append(string.Format(“{0},”,第1行));
//添加第二个地址行
sb.Append(string.Format(“{0},”,第2行));
sb.Append(string.Format(“{0},”,郊区));
Append(string.Format(“{0}{1},”,State==null?string.Empty:State.Description,Postcode));
sb.Append(string.Format(“{0}”,Country==null?string.Empty:Country.Description));
//然后将其作为单个(格式化)字符串返回
使某人返回字符串();
}
}
你会注意到我排除了State和Country,因为如果我不排除,当我调用TryUpdateModel(导入器)时,我会得到可怕的无参数构造函数异常。我的问题是:

我如何在我的行动中通过这种方式获得正确的州和国家id(或者一般来说,任何下拉列表)

为完整起见:

Address.ascx

<div class="formElementGroupVertical">
    <%: Html.LabelFor(m => m.Line1) %>
    <%: Html.EditorFor(m => m.Line1) %>
    <%: Html.ValidationMessageFor(m => m.Line1) %>
</div>
<div class="formElementGroupVertical">
    <%: Html.LabelFor(m => m.Line2) %>
    <%: Html.EditorFor(m => m.Line2) %>
    <%: Html.ValidationMessageFor(m => m.Line2) %>
</div>
<div class="formElementGroupVertical">
    <%: Html.LabelFor(m => m.Suburb) %>
    <%: Html.EditorFor(m => m.Suburb)%>
    <%: Html.ValidationMessageFor(m => m.Suburb)%>
</div>
<div class="formElementGroupVertical">
    <%: Html.LabelFor(m => m.State) %>
    <%: Html.EditorFor(m => m.State) %>
</div>
<div class="formElementGroupVertical">
    <%: Html.LabelFor(m => m.Postcode) %>
    <%: Html.EditorFor(m => m.Postcode)%>
    <%: Html.ValidationMessageFor(m => m.Postcode)%>
</div>
<div class="formElementGroupVertical">
    <%: Html.LabelFor(m => m.Country) %>
    <%: Html.EditorFor(m => m.Country) %>
</div>

m、 第1行)%%>
m、 第1行)%%>
m、 第1行)%%>
m、 第2行)%%>
m、 第2行)%%>
m、 第2行)%%>
m、 郊区)%>
m、 郊区)%>
m、 郊区)%>
m、 国家)%>
m、 国家)%>
m、 邮政编码)%%>
m、 邮政编码)%%>
m、 邮政编码)%%>
m、 国家)%>
m、 国家)%>
国家:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Web.Common.Models.Country>" %>
<%@ Import Namespace="Web.Common.Models" %>
<%@ Import Namespace="Web.Common.Service" %>
<%: Html.DropDownListFor(m => m.CodeId, new SelectList(ServiceLocatorFactory.GetCodeServiceLocator<Country>().GetAll(), "CodeId", "Description"), "Please Select")%>

m、 CodeId,新选择列表(ServiceLocatorFactory.GetCodeServiceLocator().GetAll(),“CodeId”,“Description”),“请选择”)%>
国家和国家是一样的,只是明显不同

有什么帮助吗?

简短回答: 未填充CountryId,因为DropDownList For为'For'
country=>country.CodeId

要获取CountryId,您实际上需要将下拉列表指向它:

Html.DropDownListFor(m => m.CountryId, new SelectList(ServiceLocatorFactory.GetCodeServiceLocator<Country>().GetAll(), "CodeId", "Description"), "Please Select")%>
然后以以下方式使用
DropDownFor()

<%: Html.DropDownListFor(m => m.SelectedCountryId, new SelectList(ServiceLocatorFactory.GetCodeServiceLocator<Country>().GetAll(), "CodeId", "Description"), "Please Select")%>

这种方式还意味着您需要为视图使用视图模型,而不是域模型。您的示例似乎正在使用域模型,因此您可能希望研究如何更改它。一旦你开始使用视图模型,你还需要一些东西来帮助你将视图模型映射到域模型。

好的,伙计们,我似乎有一个临时的解决方法来解决我的问题,我很想知道你的反馈,以及可能使这个解决方案更“健壮”的任何其他替代方案

在我的操作中,我检查Request.Form并查找由复杂类型的PropertyName指定的下拉列表。因此语法如下所示:

下拉列表返回的PropertyName.PropertyName.Value字段。使用这个,如果需要获取ComplexType的实例,我就可以查找存储库

我的操作粘贴在下面以供参考:

[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult Update(int id)
{
    // obtain the instance of the importer we wish to update
    var importer = serviceLocator.Get(i => i.ImporterId == id);

    // the address object doesn't bind the State and Country dropdowns so we must manually read these
    var stateCodeId = Request.Form["ImporterAddress.State.CodeId"];
    var countryCodeId = Request.Form["ImporterAddress.Country.CodeId"];

    //Perform model binding (fill the properties and validate the model)
    if (TryUpdateModel(importer))
    {
        // parse the Id fields of the selected values of the dropdowns that we've just read from the request objects
        importer.ImporterAddress.StateId = int.Parse(stateCodeId);
        importer.ImporterAddress.CountryId = int.Parse(countryCodeId);

        // and convert them to their specific code objects
        importer.ImporterAddress.State =
            ServiceLocatorFactory.GetCodeServiceLocator<State>().Get(s => s.CodeId == int.Parse(stateCodeId));
        importer.ImporterAddress.Country =
            ServiceLocatorFactory.GetCodeServiceLocator<Country>().Get(s => s.CodeId == int.Parse(countryCodeId));

        // now save the updated model
        serviceLocator.Update(importer);
    }

    // rebind the grid
    return PartialView(new GridModel(serviceLocator.GetAll().ToList()));
}
[AcceptVerbs(HttpVerbs.Post)]
[行动]
公共操作结果更新(int id)
{
//获取我们希望更新的导入程序的实例
var importer=serviceLocator.Get(i=>i.ImporterId==id);
//address对象不绑定State和Country下拉列表,因此我们必须手动读取它们
var stateCodeId=Request.Form[“ImporterAddress.State.CodeId”];
var countryCodeId=Request.Form[“ImporterAddress.Country.CodeId”];
//执行模型绑定(填写属性并验证模型)
if(TryUpdateModel(进口商))
{
//解析我们刚刚从请求对象读取的下拉列表的选定值的Id字段
importer.ImporterAddress.StateId=int.Parse(stateCodeId);
importer.ImporterAddress.CountryId=int.Parse(countryCodeId);
//并将它们转换为特定的代码对象
importer.ImporterAddress.State=
ServiceLocatorFactory.GetCodeServiceLocator().Get(s=>s.CodeId==int.Parse(stateCodeId));
进口商。进口商地址。国家=
ServiceLocatorFactory.GetCodeServiceLocator().Get(s=>s.CodeId==int.Parse(countryCodeId));
//现在保存更新的模型
serviceLocator.Update(导入程序);
}
//重新绑定网格
返回PartialView(新的GridModel(serviceLocator.GetAll().ToList());
}
<
public ViewResult Save(AddressViewModel addressVM)
{
  var address = new Address() { Country = countriesStore.ById(addressVM.SelectedCountryId) };
  address.Save();

  ...
}
[AcceptVerbs(HttpVerbs.Post)]
[GridAction]
public ActionResult Update(int id)
{
    // obtain the instance of the importer we wish to update
    var importer = serviceLocator.Get(i => i.ImporterId == id);

    // the address object doesn't bind the State and Country dropdowns so we must manually read these
    var stateCodeId = Request.Form["ImporterAddress.State.CodeId"];
    var countryCodeId = Request.Form["ImporterAddress.Country.CodeId"];

    //Perform model binding (fill the properties and validate the model)
    if (TryUpdateModel(importer))
    {
        // parse the Id fields of the selected values of the dropdowns that we've just read from the request objects
        importer.ImporterAddress.StateId = int.Parse(stateCodeId);
        importer.ImporterAddress.CountryId = int.Parse(countryCodeId);

        // and convert them to their specific code objects
        importer.ImporterAddress.State =
            ServiceLocatorFactory.GetCodeServiceLocator<State>().Get(s => s.CodeId == int.Parse(stateCodeId));
        importer.ImporterAddress.Country =
            ServiceLocatorFactory.GetCodeServiceLocator<Country>().Get(s => s.CodeId == int.Parse(countryCodeId));

        // now save the updated model
        serviceLocator.Update(importer);
    }

    // rebind the grid
    return PartialView(new GridModel(serviceLocator.GetAll().ToList()));
}