ASP.NET MVC 绑定模型
ASP.NET MVC binding model
假设我有这些模型:
public class FilterModel
{
FilterPersonModel Person { get; set; }
FilterJobModel Job { get; set; }
}
public class FilterPersonModel
{
public string Name { get; set; }
public int Age { get; set; }
}
public class FilterJobModel
{
public string CompanyName { get; set; }
public string JobTitle { get; set; }
}
我有以下操作:
public ActionResult Search(FilterModel model)
{
//TODO
}
最后,我的操作是用以下 url 调用的:http://mysite/myController/Search?Name=Bob&Age=32&CompanyName=Amazon&JobTitle=Developer
当我调试时,我的模型为空,无法识别 Person 和 Job 属性。
在不改变任何东西的情况下,我是否必须创建一个模型活页夹或者是否有其他解决方案?
如果有,是哪一个?
你问的是不可能的。 某些东西 必须改变,无论是 URL 还是 action/models。由于 URL 是 public 界面,我建议创建一个视图模型来匹配 URL,然后您可以从那里映射到所需的模型。例如:
public class FilterViewModel
{
public string Name { get; set; }
public int Age { get; set; }
public string CompanyName { get; set; }
public string JobTitle { get; set; }
}
然后:
public ActionResult Search(FilterViewModel model)
{
var filter = new FilterModel
{
Person = new FilterPersonModel
{
Name = model.Name,
Age = model.Age
},
Job = new FilterJobModel
{
CompanyName = model.CompanyName,
JobTitle = model.JobTitle
}
};
// do whatever with `filter`
}
假设我有这些模型:
public class FilterModel
{
FilterPersonModel Person { get; set; }
FilterJobModel Job { get; set; }
}
public class FilterPersonModel
{
public string Name { get; set; }
public int Age { get; set; }
}
public class FilterJobModel
{
public string CompanyName { get; set; }
public string JobTitle { get; set; }
}
我有以下操作:
public ActionResult Search(FilterModel model)
{
//TODO
}
最后,我的操作是用以下 url 调用的:http://mysite/myController/Search?Name=Bob&Age=32&CompanyName=Amazon&JobTitle=Developer
当我调试时,我的模型为空,无法识别 Person 和 Job 属性。 在不改变任何东西的情况下,我是否必须创建一个模型活页夹或者是否有其他解决方案? 如果有,是哪一个?
你问的是不可能的。 某些东西 必须改变,无论是 URL 还是 action/models。由于 URL 是 public 界面,我建议创建一个视图模型来匹配 URL,然后您可以从那里映射到所需的模型。例如:
public class FilterViewModel
{
public string Name { get; set; }
public int Age { get; set; }
public string CompanyName { get; set; }
public string JobTitle { get; set; }
}
然后:
public ActionResult Search(FilterViewModel model)
{
var filter = new FilterModel
{
Person = new FilterPersonModel
{
Name = model.Name,
Age = model.Age
},
Job = new FilterJobModel
{
CompanyName = model.CompanyName,
JobTitle = model.JobTitle
}
};
// do whatever with `filter`
}