我一直在尝试将模型传递给带有表单的局部视图。某些模型字段已在GET请求中分配。当表单加载时,我可以看到模型字段值,但之后
提交表单我在此行中收到此错误:@Html.Hidden("From",Model.From):
对象引用未设置为对象的实例
为什么在提交时为这两个字段分配了null?
我的控制器:
[HttpGet]
public ActionResult SendPrivateMessage(string from, List<string> to)
{
// two of the fields are already assigned
return PartialView("SendMessage", new MessageModel(from,to));
}
[HttpPost]
public ActionResult SendPrivateMessage(MessageModel m)
{
string fullname = "";
LoginModel loginData = (LoginModel)(Session["user"]);
if (Session["user"] != null)
{
fullname = loginData.LoginDS.Tables[0].Rows[0][loginData.LoginDS.Tables[0].Columns["fullname"].Ordinal].ToString();
}
m.fullname = fullname;
m.Send();
return PartialView("SendMessage");
}
部分视图:
@model HaifanetMobile.Models.MessageModel
<div id="contact_form">
<a id="back_contact" href="#" style="float:left">
<img style="height:20px; width:30px;" src="~/Images/back_btn.gif" alt="back" />.
</a>
<div id="contactus_title">
<div id="close_contactus" style="float:right"><img style="height:20px; width:20px;" src="~/Images/close_btn.gif" /></div>
</div>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<br />
<fieldset>
@Html.Hidden("From", Model.From) //this is where I get the error
@Html.Hidden("To", Model.To)//this is where I get the error
<div>
@Html.TextBoxFor(m => m.Subject, new { @class = "", placeholder = "subject:", id = "msg_subject", onfocus = "this.placeholder = ''", onblur = "this.placeholder = 'subject:'" })
@Html.ValidationMessageFor(m => m.Subject, "required")
</div>
<div>
@Html.TextAreaFor(m => m.Content, new { @class = "", id = "msg_textarea" })
@Html.ValidationMessageFor(m => m.Content, "required")
</div>
</fieldset>
<p>
<input type="submit" value="send" />
</p>
}
</div>
模特:
public class MessageModel
{
public string From { get; set; }
public List<string> To { get; set; }
public string Subject {get; set;}
public string Content { get; set; }
public string fullname { get; set; }
public MessageModel(string from, List<string> to)
{
// TODO: Complete member initialization
this.From = from;
this.To = to; ;
}
public MessageModel() {
}
public void Send()
{
ServiceReference2.WebService1Soap ws = new ServiceReference2.WebService1SoapClient();
if (!ws.SendMessage(this.From, this.Content, this.Subject, this.To.ToArray() ,this.fullname))
throw new Exception();
}
}
提前致谢
答案 0 :(得分:5)
您忘记将模型传递给您的视图。
当您返回此视图时,而不是:
return PartialView("SendMessage");
你必须这样做:
return PartialView("SendMessage", m);
m
是您的模型。这就是你的视图中模型为空的原因。