gpt4 book ai didi

asp.net-mvc-4 - 提交表单时 MVC : System. NullReferenceException 模型

转载 作者:行者123 更新时间:2023-12-02 01:07:06 28 4
gpt4 key购买 nike

我一直在尝试将模型传递给带有表单的分部 View 。某些模型字段已在 GET 请求中分配。当表单加载时我可以看到模型字段值但是之后提交表单我在这一行中收到此错误:@Html.Hidden("From",Model.From):

Object reference not set to an instance of an object

为什么这两个字段在提交时被赋值为空?

我的 Controller :

  [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");
}

局部 View :

@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();

}
}

提前致谢

最佳答案

您忘记将模型传递给您的 View 。

当你返回这个 View 时,而不是这个:

return PartialView("SendMessage");

你必须这样做:

return PartialView("SendMessage", m);

m 是您的模型。这就是模型在您的 View 中为空的原因。

关于asp.net-mvc-4 - 提交表单时 MVC : System. NullReferenceException 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21254846/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com