2015-04-16 53 views
0

有一种表单将值传递到Ajax脚本中,然后传递给控制器​​。所有手动输入的工作,但在下拉列表中的任何东西似乎都不会被传回。将选定的DropDownListFor值传递给Ajax

因此,例如:当用户提交表单

,我在这里捕捉他们:

<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() 

这则

<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> 

下拉列表返回标题的列表击中此:

[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属性是用于调试的值,并在首字母都有一个值进入nameTitle不,我不能明白为什么

我有这个在未来的形式,现在显示的值:

<div> Value check for Title: @ViewBag.NameTitle </div> 
<div> Value check for Initials: @ViewBag.Initials </div> 

任何人都可以看到我在哪里呢?

+0

你错过了“<”char?在div class =“div-dropdown-menu” –

回答

1

您正在传递一个由htmlAttributesDropDownListFor组成的匿名对象。这仅用于在使用EditorFor时添加附加属性。对于像DropDownListFor,你只是通过匿名对象和属性:

@Html.DropDownListFor(model => model.Title, (SelectList)ViewBag.NameTitle, "Please select a title", new { @class = "dropdown", id = "txtTitle" }) 

当你拥有了它,现在,该ID是从来没有被设置的选择元素,所以价值没有被你的JavaScript选择。

+0

邪恶的感谢很多队友! – JQuery