本文介绍了将值分配到列表< object>在模型类中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
public class Parameter
{
public int Id {get;set;}
public string name {get;set;}
public List<Phonenumber> Phonenumbers{get;set}
}
public class Phonenumber
{
public string number1 {get;set;}
public string number2 {get;set;}
public string number3 {get;set;}
}
public ActionResult SmeDirPage(Phonenumber number)
{
Parameter para = new Parameter ();
// How do i assign value to para.Phonenumbers.number1
}
我尝试过:
请问如何将值传递到此列表
What I have tried:
Please how can i pass values to this list
public ActionResult SmeDirPage(Phonenumber number)
{
Parameter para = new Parameter ();
foreach(var item in para.Phonenumbers) // Error **Object reference not set to an instance of an object**
{
item.number1 = number.number1;
item.number2 = number.number2;
item.number3 = number.number3;
}
}
推荐答案
public class Parameter
{
public int Id {get;set;}
public string name {get;set;}
public List<Phonenumber> Phonenumbers{get;set}
public Parameter()
{
this.Phonenumbers = new List<Phonenumber>();
}
}
Quote:
请问如何将值传递给此列表
Please how can i pass values to this list
您不需要循环为您的值分配值列表
因为它已经预期某种类型 Phonenumber
。你需要做的就是这样:
You don't need a loop to assign values to your List
because it's already expecting a type of Phonenumber
. What you need to do is simply just like this:
var phoneNumbers = new List<Phonenumber>();
phoneNumbers.Add(numbers);
然后您可以将 phoneNumbers
值分配给您的参数
这样的对象:
You can then assign the phoneNumbers
value to your Parameter
object like this:
Parameter para = new Parameter();
para.Id = 1;
para.name = "Vynn Markus";
para.Phonenumbers = phoneNumbers;
完全放入它们,你的整个 ActionResult
方法现在看起来像这样:
To put them altogether, your whole ActionResult
method would now look something like this:
public ActionResult SmeDirPage(Phonenumber numbers)
{
var phoneNumbers = new List<Phonenumber>();
phoneNumbers.Add(numbers);
Parameter para = new Parameter();
para.Id = 1;
para.name = "Vynn Markus";
para.Phonenumbers = phoneNumbers;
}
这篇关于将值分配到列表< object>在模型类中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!