如何将模型值和javascript值传递给控制器

时间:2012-12-12 07:51:02

标签: javascript jquery ajax asp.net-mvc-3

我正在提交具有性别css下拉列表的表单如何将性别选择值提交给控制器我得到的值为null

<div class="regi-field-set">

            <div id="ddlgender" class='selectBox' tabindex="7">

                      <span class='selected' id="gender">gender</span> 
        <span class='selectArrow'>&#9660</span>
                     <div id="disableasterisk5" style="padding-bottom:8px"><span class="required">*</span></div>
                  <div class="selectOptions" id="genderSelectOptions">

                <span class="selectOption" id="ddlgen">male</span>
                      <span class="selectOption" id="ddlgen1">female</span>


        </div>
                 </div>

<div class="regi-field-set">
                   @Html.TextBoxFor(model => model.DOB, new { @class = "jq_watermark", placeholder = "date of birth", tabindex = "8",id = "DOB",title = "please enter date of birth" })
                   <div id="disableasterisk7"><span class="required">*</span></div>
                  <div class="clear"></div>
                  @Html.ValidationMessageFor(model => model.DOB)
              </div>

如何将两个值传递给控制器​​表单中的所有其他字段都使用html.helper字段只有性别字段是css实现

有没有办法将整个模型和性别选择值传递给控制器​​

请帮助

2 个答案:

答案 0 :(得分:0)

如果我理解了你的问题,那么传递给查看“模型”和下拉列表中使用的其他内容列表的答案可以通过以下代码完成:

控制器

         ....
         var model = service.GetMyThing(id);
         var genderList= service.GetGenders().Select(p => 
                   new SelectListItem { Value = p.Id.ToString(), Text = p.Name }).ToList();
         ViewBag.GenderList = genderList; 
         return View(model);

查看

         ....
         @Html.DropDownList("GenderId",(IEnumerable<SelectListItem>)ViewBag.GenderList)
         ....
          <div class="regi-field-set">
               @Html.TextBoxFor(model => model.DOB, new { @class = "jq_watermark", placeholder = "date of birth", tabindex = "8",id = "DOB",title = "please enter date of birth" })
               <div id="disableasterisk7"><span class="required">*</span></div>
              <div class="clear"></div>
              @Html.ValidationMessageFor(model => model.DOB)
          </div>

注意:这不是唯一的解决方案,自定义HTMLHelpers可用于绘制组合。

答案 1 :(得分:0)

使用ajax你可以做到这一点:不要使用表格&amp;在标签中声明您的属性:

<a href="someLink">@Model.idText</a>
<input type="text" id="textValue"/>
<input type="submit" id="btnSubmit"/>

jquery的:

 $(function (e) {
        //    Insert
        $("#btnSubmit").click(function () {

            $.ajax({
                url: "some url path",
                type: 'POST',
                data: { textField: $('#textValue').val(), idField: '@Model.idText' },
                success: function (result) {
                    //some code if success
                },
                error: function () {
                    //some code if failed
                }
            });
            return false;
        });
      });

希望它会帮助你