I’ve got an MVC 3 form in a strongly typed view where one of the fields I need submitted is inside of a jQuery dialog. I have not been able to get this field to be part of the POST parameters submitted. Why oh why?
The View:
@model My.Models.DialogFieldModel
@{
ViewBag.Title = "Index";
}
<script type="text/javascript">
$(document).ready(function () {
$('#aDialog').dialog({
autoOpen: true,
height: 250, width: 400,
modal: true,
buttons: {
"Ok!": function () {
$(this).dialog("close");
}
}
});
});
</script>
<h2>Index</h2>
@using (Html.BeginForm("PostDialogField", "DialogField"))
{
@Html.ValidationSummary(true)
<fieldset>
@Html.HiddenFor(m => m.ID)
@Html.DisplayFor(m => m.message)
<div id="aDialog">
<h3>Fill in this message!</h3>
<div class="editor-field">
@Html.EditorFor(m => m.message)
</div>
</div>
<p><input type="submit" value="Submit Message" /></p>
</fieldset>
}
The Model:
using System;
namespace My.Models
{
public class DialogFieldModel
{
public int ID { get; set; }
public String message { get; set; }
public DialogFieldModel()
{
message = "Default";
}
}
}
The controller:
using System;
using System.Web;
using System.Web.Mvc;
using WellTrkd.Models;
namespace My.Controllers
{
public class DialogFieldController : Controller
{
public ActionResult Index()
{
DialogFieldModel dfm = new DialogFieldModel(); // set default message
return View(dfm);
}
[HttpPost]
public ActionResult PostDialogField(DialogFieldModel dfm)
{
String message = dfm.message;
if (message != "Default")
//Yay!
return RedirectToAction("Index");
else // Boo
return RedirectToAction("Index");
}
}
}
Unfortunately the #message field is never submitted along with the rest of the HTML POST parameters (checked in network tab of chrome dev view) unless I take it out of the dialog. The result is that in the PostDialogField action dfm.message contains the “Default” string, even if I’ve changed the message in the dialog.
I know I could add a hidden field to the form that is kept synchronized with the field in the dialog, but I feel I’m missing something. Any thoughts oh wise ones?
Your problem is that the element you turn into a dialog is moved out of the form towards a new dialog-element at the bottom of the DOM. And since it’s not part of the form any more, it won’t be submitted when the form is submitted.
If you’d destroy the dialog when closing it, it would be moved back to where it was, but I can’t see if that’s what is desired. The other option is to sync elements.