Asp.net mvc 4 mvc4中的模型值为空
我使用的是post方法,我试图将textbox的值发布到数据库中,为此我执行了所有必要的步骤,但在该post方法中,我的模型为null。找到下面的代码, 我的简单控制器Asp.net mvc 4 mvc4中的模型值为空,asp.net-mvc-4,Asp.net Mvc 4,我使用的是post方法,我试图将textbox的值发布到数据库中,为此我执行了所有必要的步骤,但在该post方法中,我的模型为null。找到下面的代码, 我的简单控制器 [HttpPost] public ActionResult Index(QuestionBankModel question) { return View(); } 我的模型 public class QuestionBankModel { public st
[HttpPost]
public ActionResult Index(QuestionBankModel question)
{
return View();
}
我的模型
public class QuestionBankModel
{
public string question { get; set; }
}
我的看法
@model OnlinePariksha.Models.QuestionBankModel
@{
var CustomerInfo = (OnlinePariksha.Models.UserLoginModel)Session["UserInfo"];
}
@{
ViewBag.Title = "Index";
}
@{
Layout = "~/Views/Shared/Admin.cshtml";
}
@using (Html.BeginForm("Index", "AdminDashboard", FormMethod.Post))
{
<div id="questionsDiv" style="width:100%; display:none;">
<div style="width:200px">
<table style="width:100%">
<tr>
<td><span><b>Question:</b></span></td>
<td>
@Html.TextBox(Model.question, new Dictionary<string, object> { { "class", "textboxUploadField" } })
</td>
</tr>
</table>
</div>
<div class="clear"></div>
<div>
<input type="submit" class="sucessBtn1" value="Save" />
</div>
</div>
}
@model online pariksha.Models.QuestionBankModel
@{
var CustomerInfo=(OnlinePariksha.Models.UserLoginModel)会话[“UserInfo”];
}
@{
ViewBag.Title=“Index”;
}
@{
Layout=“~/Views/Shared/Admin.cshtml”;
}
@使用(Html.BeginForm(“Index”,“AdminDashboard”,FormMethod.Post))
{
问题:
@TextBox(Model.question,新字典{{“class”,“textboxUploadField”})
}
我错过了什么吗?你试过使用@HTML.TextBoxFor吗
@Html.TextBoxFor(m=>m.question,new Dictionary<string, object> { { "class", "textboxUploadField" } })
@Html.TextBoxFor(m=>m.question,新字典{{“class”,“textboxUploadField”})
Html.TextBox使用不正确,因为第一个参数是TextBox的名称,而您正在传递question的值。我会用这个来代替:
@Html.TextBoxFor(m => m.question)
您的问题是POST方法参数名称与模型属性的名称相同(因此模型绑定失败)。将方法签名更改为
public ActionResult Index(QuestionBankModel model)
{
...
}
或与模型特性不同的任何其他参数名称
作为说明,
DefaultModelBinder
首先初始化QuestionBankModel
的一个新实例。然后检查表单(和其他)值,并查看question=“SomeStringYouEntered”
。然后,它搜索名为question
(以设置其值)的属性。它找到的第一个是您的方法参数,因此它在内部执行QuestionBankModel question=“SomeStringYouEntered”
失败(您无法为复杂对象指定串接),模型参数现在变为null
,因此QuestionBankModel有1个属性:question。在HttpPost上点击Index操作时,该问题的值为空?试着在文本框中键入一些内容,然后单击“提交”怎么样?