有一个表单,其中值被传递到Ajax脚本然后传递给控制器。所有手动输入的都可以使用,但下拉列表中的任何内容似乎都没有被传回。
例如:
<div style="display: table-row;">
<div class="div-dd-label-text" , style="display: table-cell">
@Html.LabelFor(model => model.Title)
</div>
<div class="div-dropdown-menu" , style="display: table-cell">
@Html.DropDownListFor(model => model.Title, (SelectList)ViewBag.NameTitle, "Please select a title", new { htmlAttributes = new { @class = "dropdown", id = "txtTitle" } })
</div>
<div class="div-val-cell" , style="display: table-cell">
@Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
</div>
<div class="div-label-text" , style="display: table-cell">
@Html.LabelFor(model => model.Initials)
</div>
<div class="div-EditorFor" , style="display: table-cell">
@Html.EditorFor(model => model.Initials, new { htmlAttributes = new { @class = "div-form-control", id = "txtInitials" } })
</div>
<div class="div-val-cell" , style="display: table-cell">
@Html.ValidationMessageFor(model => model.Initials, "", new { @class = "text-danger" })
</div>
</div>
下拉列表返回标题列表:
我在用户提交表单时将其捕获:
<script>
var urlAction = "@Url.Content("~/Treeview/_NewEmpDetails")";
function AjaxGoodRedirect(urlAction) {
console.log(urlAction);
var form = $("#myForm");
form.validate();
if (form.valid()) {
$.ajax({
type: "POST",
url: urlAction,
data: JSON.stringify({
Title: $("#txtTitle").val()
, Initials: $("#txtInitials").val()
然后点击这个:
[HttpPost]
public ActionResult _NewEmpDetails(NewEmp.First model)
{
if (ModelState.IsValid)
{
var sessionValues = new MySessionValues();
sessionValues.Employee = model;
Session["MySessionValues"] = sessionValues;
}
return Json(new { ok = true, newurl = ("/Treeview/_NewEmpSecond") }, "application/json", JsonRequestBehavior.DenyGet);
}
重定向到下一个表单
public ActionResult _NewEmpSecond()
{
var sessionValues = Session["MySessionValues"] as MySessionValues;
ViewBag.NameTitle = sessionValues.Employee.Title;
ViewBag.Initials = sessionValues.Employee.Initials;
return PartialView();
}
目前我将ViewBag
属性设置为调试值,而在输入时,姓名标题没有输入值,而我无法解决原因
我在下一个表单中有这个显示现在的值:
<div> Value check for Title: @ViewBag.NameTitle </div>
<div> Value check for Initials: @ViewBag.Initials </div>
谁能看到我哪里出错?
答案 0 :(得分:1)
您正在传递由htmlAttributes
到DropDownListFor
组成的匿名对象。这仅用于在使用EditorFor
时添加其他属性。对于类似DropDownListFor
的内容,您只需传递具有以下属性的匿名对象:
@Html.DropDownListFor(model => model.Title, (SelectList)ViewBag.NameTitle, "Please select a title", new { @class = "dropdown", id = "txtTitle" })
正如您现在所做的那样,id永远不会在select元素上设置,因此您的JavaScript不会选择该值。