使用多个数组初始化模型。
我已经尝试初始化,但它不起作用。
namespace ArrayTest.Models
{
public class Question
{
public string question { get; set; }
public string[] option { get; set; }
public string[] score { get; set; }
}
}
public class DefaultController : Controller
{
public ActionResult Index()
{
IEnumerable<Question> x = new List<Question>
{
new Question(){ question = "Question1", option = { "abc","cde","efg"}, score = { "abc", "cde", "efg" } },
new Question(){},
new Question(){},
new Question(){}
};
return View(x);
}
}
我希望此模型被初始化并发送到视图。
string[]
没有.Add()
方法,因此option = { "abc", "cde", "efg"}
不起作用。您需要创建数组并初始化数组:
var list = new List<Question>
{
new Question()
{
question = "Question1",
option = new string[] { "abc", "cde", "efg"},
score = new string[] { "abc", "cde", "efg" }
},
new Question(){},
new Question(){},
new Question(){}
};
步骤 1 :在模态中添加一个构造函数,如下所示,
public class Question
{
public string question { get; set; }
public string[] option { get; set; }
public string[] score { get; set; }
public Question(string question, List<string> option, List<string> score)
{
this.question = question;
this.option = option.ToArray();
this.score = score.ToArray();
}
}
第 2 步:修改控制器方法,如下所示,
IEnumerable<Question> x = new List<Question> {
new Question("Question1", new List<string>{"cde","efg"}, new List<string> { "abc", "cde", "efg" }),
new Question("Question2", new List<string>{"cde","efg"}, new List<string> { "abc", "cde", "efg" }) } ;
如果使用此列表,则可以使用 。Add(( 方法也是如此。