我正在开发一个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)
}
我有一个像这样的viewmodel:
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})
但是当我看到视图源时,Value为null
我尝试使用:
@Html.Hidden("m.m_newIVR.Account", Model.accountID)
并显示填充了m_newIVR.Account。
然后我将表单发布到控制器此操作
[HttpPost]
public ActionResult AddIVR(AccountDetailsViewModel model)
{
return RedirectToAction("AccountDetails", "mycontroller")
}
虽然我看到AccountId在视图中填充(使用viewsource),但在post action方法中,model.m_newIVR.Account的值为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>
我的问题是:
请建议。
答案 0 :(得分:1)
现在我能够回答你的问题为什么它适用于Html.Hidden而不适用于Html.HiddenFor。
如果你想在ViewModel中使用HiddenFor设置m_newIVR.Account,只需使用以下内容。
@Html.HiddenFor(m =>m.m_newIVR.Account)
我的工作样本
<强>模型强>
public class AccountDetailsViewModel
{
public string AccountId { get; set; }
public IVRS m_newIVR { get; set; }
}
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; }
}
控制器操作
[HttpGet]
public IActionResult Index1()
{
AccountDetailsViewModel model = new AccountDetailsViewModel();
//model.AccountId = "1222222";
model.m_newIVR = new IVRS();
model.m_newIVR.Account = "122222";
return View(model);
}
[HttpPost]
public IActionResult Index1(AccountDetailsViewModel model)
{
return View(model);
}
查看(Index1.cshtml)
@model WebApplication2.Controllers.AccountDetailsViewModel
@using (Html.BeginForm())
{
@Html.HiddenFor(m =>m.m_newIVR.Account)
<input type="submit" />
}
// Sample Out