【发布时间】:2017-01-22 22:23:27
【问题描述】:
我正在开发一个 asp.net MVc 核心应用程序。我有一个带有这样的表单元素的弹出窗口:
@using (Html.BeginForm("AddIVR", "ITPVoice", FormMethod.Post, new { role = "form" }))
{
@*@Html.HiddenFor(m =>m.m_newIVR.Account, new { @value= Model.accountID})*@
@Html.Hidden("m.m_newIVR.Account", Model.accountID)
}
我有一个这样的视图模型:
public class AccountDetailsViewModel
{
public IVRS m_newIVR { get; set; }
}
和这样的IVRS模型类:
public class IVRS
{
[JsonProperty("_id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("description")]
public string Description { get; set; }
[JsonProperty("account")]
public string Account { get; set; }
}
我正在尝试像这样在我的视图中填充它:
@Html.HiddenFor(m =>m.m_newIVR.Account, new { @value= Model.accountID})
但是当我看到查看源代码时,值为空
我尝试使用:
@Html.Hidden("m.m_newIVR.Account", Model.accountID)
它显示 m_newIVR.Account 已填充。
然后我发布表单以控制此操作
[HttpPost]
public ActionResult AddIVR(AccountDetailsViewModel model)
{
return RedirectToAction("AccountDetails", "mycontroller")
}
虽然我看到 AccountId 在视图中填充(使用视图源),但在 model.m_newIVR.Account 的 post action 方法中值为 null。
HTML 输出如下所示:
<div id="edit-ivrs-modal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
<div class="modal-dialog">
<form action="/ITPVoice/AddIVR" method="post" role="form"> <div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add IVR</h4>
<input id="m_newIVR_Account" name="m_newIVR.Account" type="hidden" value="" />
<input id="AccountId" name="AccountId" type="hidden" value="56f5e3d77ea022a042665be1" />
</div>
<div class="modal-body">
</div>
</div>
我的问题是:
- 为什么 html.hiddenfor 没有设置模型变量的值?
- 虽然 html.hidden 是设置值,为什么在 post action 方法中无法访问?
请提出建议。
【问题讨论】:
-
永远不要使用
new { @value= Model.accountID}设置value属性。目前尚不清楚您尝试绑定到什么,但 ir 应该只是@Html.HiddenFor(m =>m.m_newIVR.Account)并且您在将模型传递给视图之前在控制器方法中设置了Account的值。 -
而您的
Html.Hidden()不起作用,因为它生成name="m.m_newIVR.Account"并且您的模型不包含名为m的属性 -
正在使用局部视图吗?什么@model 在您的页面顶部?我怀疑是因为你说 Model.AccountId 的价值,而在 HiddenFor 你使用不同的模型。我试过它对我的模型都适用。
-
我的 razor View 在顶部有这个模型声明 @model ITPAdmin.Models.ViewModels.AccountDetailsViewModel。我有两个帐户属性。一个直接在 AccountDetailsViewModel 中,另一个在 AccountDetailsViewModel.m_newIVR.Account 中。
-
我尝试像这样设置 AccountId model.m_newIVR.Account = model.accountID;但在弹出窗口打开之前查看,但视图中为空。
标签: c# asp.net asp.net-mvc asp.net-core