我已经阅读了关于这个问题的几个问题和答案,但没有一个让我更接近解决这个问题。我的问题是我似乎无法将RadioButtonFor
检查值保留到post action方法。它有很多不相关的东西,所以我会尝试将其归结为相关问题。
所以我有ViewModel
这样:
public class QEventHandlerVM
{
//Removed unrelated
public QueueEventHandlerModel QEventHandler { get; set; }
public string SelectedOption { get; set; }
}
编辑视图的Get Method
。我在这里设置SelectedOption
所以我可以在前端处理它。任务是根据SelectedOption
值显示和隐藏div。据我所知,这部分工作,值已设置并通过jQuery在视图中使用。
[HttpGet]
public ActionResult Edit(int id)
{
try
{
//Removed unrelated...
QueueEventHandlerModel model;
QEventHandlerVM vm = new QEventHandlerVM();
ApiCommunicator.Get("QueueEventHandlers/" + id, out model);
vm.QEventHandler = model;
if (...)
vm.SelectedOption = "toQueue";
if (...)
vm.SelectedOption = "redirection";
if (...)
vm.SelectedOption = "hangup";
return View(vm);
}
catch (HttpResponseUnsuccessfulException e){...}
}
Edit view
简化:
@model Foo.WebSites.Web.Views.QueueEventHandlers.QEventHandlerVM
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
//Unrelated stuff...
@Html.HiddenFor(s => s.SelectedOption)
@Html.RadioButtonFor(s => s.SelectedOption, "toQueue", new { id = "rdToQueue", @class = "q-event" })
<label for="rdToQueue">Transfer call to queue</label>
@Html.RadioButtonFor(s => s.SelectedOption, "redirect", new { id = "rdRedirect", @class = "q-event" })
<label for="rdRedirect">Transfer call to destination</label>
@Html.RadioButtonFor(s => s.SelectedOption, "hangup", new { id = "rdHangup", @class = "q-event" })
<label for="rdHangup">Hangup</label>
<button type="submit" class="btn btn-primary btn-sm">Save</button>
}
Post
方法
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(QEventHandlerVM model, int id)
{
if (!ModelState.IsValid) {... return View(model); }
if (model.SelectedOption == "hangup" || model.SelectedOption == "redirection")
{
model.QEventHandler.QueueId = null;
}
else if (model.SelectedOption == "toQueue")
{
model.QEventHandler.Phrase = string.Empty;
model.QEventHandler.Redirection = string.Empty;
}
else if (model.SelectedOption == "hangup")
{
model.QEventHandler.Redirection = string.Empty;
model.QEventHandler.QueueId = null;
}
try {// Update}
catch (HttpResponseUnsuccessfulException e){...}
}
现在,SelectedOption
值与Get
方法的值相同。我可能已经错过了一些简单的事情,并且最有可能采取更好的方式。
提前致谢。
答案 0 :(得分:2)
这是因为您的HiddenFor
媒体资源的SelectedOption
和相关编辑字段。只需删除HiddenFor
,这应该有效:
@Html.HiddenFor(s => s.SelectedOption)