我的寄主在传回表格时表现得非常好,但是我建造的表格却没有传回来。我不确定我的工作方式与visual studio提供的注册页面不同。它调用正确的http post方法,但传递的值为null。谢谢你的帮助。我只是希望该模型回发到控制器动作结果。
控制器
[HttpGet]
public ActionResult Support()
{
ViewBag.Message = "Your app description page.";
return View();
}
[AllowAnonymous]
[HttpPost, ValidateSpamPrevention]
public ActionResult Support(QuickEmailModel email)
{
if (ModelState.IsValid)
{
return View("thankyou", email);
}
return View(email);
}
模型
public class QuickEmailModel
{
[DataType(DataType.EmailAddress)]
[EmailAddress]
public string Email { get; set; }
[Required]
public string Subject { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string Description { get; set; }
[Display(Name = "Company (Optional):")]
public string Company { get; set; }
}
}
Top of View
@using PoliteCaptcha
@model Models.QuickEmailModel
@{
ViewBag.Title = "Support";
}
表格
的底部 @using (Html.BeginForm())
{
@Html.ValidationSummary()
<div class="control-group">
<label class="control-label">
@Html.LabelFor(x => x.Company, "Company (Optional):", new { @class = "control-label" })</label>
<div class="controls">
@Html.TextBoxFor(x => x.Company, new { @class = "span4" })
</div>
</div>
<div class="control-group">
@Html.LabelFor(x => x.Email, "Email:", new { @class = "control-label" })
<div class="controls">
@Html.TextBoxFor(x => x.Email, new { @Class = "span4" })
</div>
</div>
<div class="control-group">
<label class="control-label">
@Html.LabelFor(x => x.Subject, "Subject:", new { @class = "control-label" })</label>
<div class="controls">
@Html.TextBoxFor(x => x.Subject, new { @class = "span4" })
</div>
</div>
<div class="control-group">
<label class="control-label">
@Html.LabelFor(x => x.Subject, "Description:", new { @class = "control-label" })</label>
<div class="controls">
@Html.TextAreaFor(x => x.Description, new { @class = "span4", @rows = "6", id = "txtDescription" })
</div>
</div>
@Html.SpamPreventionFields()
<input type="submit" class="btn btn-success" id="btnSubmit" value="Submit" style="margin-right: 15em;
float: right;" />
}
答案 0 :(得分:3)
我认为问题是您的参数名称与您的某个字段名称(电子邮件)相同。将Method参数名称重命名为model(或除电子邮件之外的其他内容)。
我认为发生的事情是MVC模型绑定器看到名为“email”的发布值,并且它试图将其分配给同名的参数,但由于它不是字符串,因此无法执行此操作。因此它指定一个空值。
此外,模型绑定不区分大小写,因此电子邮件和电子邮件是相同的。
答案 1 :(得分:0)
问题是模型映射器无法将POST请求中的表单名称/值对映射到QuickEmailModel对象的实例,而只是忽略它们。检查在Firebug或其他工具中发送的POST请求,名称/值对的名称是什么?
你应该改变你的观点:
@{ var email = ....; }
<label class="control-label">
@Html.LabelFor(x => email.Company, "Company (Optional):", new { @class = "control-label" })
</label>
<div class="controls">
@Html.TextBoxFor(x => email.Company, new { @class = "span4" })
</div>
因为POST动作参数的名称是&#34; email&#34;。我认为这应该强制形成param名称为&#34; email.Company&#34;等等。如果没有,请尝试其他变体
@Html.TextBox("email.Company", model.Company)