使用jquery将模型从视图传递到控制器

时间:2012-09-19 08:31:45

标签: asp.net-mvc-3 model-view-controller jquery

我有一个观点

@using staffInfoDetails.Models
@model staffInfo

<link href="../../Content/myOwn.css" rel="stylesheet" type="text/css" />
@{staffInfo stf = Model; 
  }

<div id="education1">
@using (Html.BeginForm("addNewEdu","Home",FormMethod.Post))
{
    @Html.HiddenFor(x=>x.StaffId)
    <table>    
    <tr>
        <th>Country</th>
        <th>Board</th>
        <th>Level</th>
        <th>PassedYear</th>
        <th>Division</th>
    </tr>     
    <tr> 
       @Html.EditorFor(x => x.eduList)
    </tr>
    <tr>
    @*<td><input type="submit" value="create Another" id="addedu"/> </td>*@
    @*<td>@Html.ActionLink("Add New", "addNewEdu", new {  Model })</td>*@    
    </tr>
    </table>  
}
<button id="addedu">Add Another</button>
</div>

我想使用jquery将模型staffInfo传递给控制器​​,如下所示

<script type="text/javascript">
    $(document).ready(function () {
        $("#addedu").live('click', function (e) {
//            e.preventDefault();           
            $.ajax({
                url: "Home/addNewEdu",
                type: "Post",
                data: { model: stf },//pass model
                success: function (fk) {
                    //                    alert("value passed");
                    $("#education").html(fk);
                }

            });
        });
    });
</script>

jquery似乎只传递元素而不是整个模型,所以如何将模型从视图传递给控制器​​,这样我就不必在jquery中编写整个参数列表

3 个答案:

答案 0 :(得分:5)

您可以使用此

为表单提供ID
@using (Html.BeginForm("addNewEdu", "Home", FormMethod.Post, new { id = "addNewEduForm" }))
{

}

然后在剧本中

<script type="text/javascript">
    $('#addedu').click(function(e) {
      e.preventDefault();
      if (form.valid()) { //if you use validation
        $.ajax({
          url: form.attr('action'),
          type: form.attr('method'),
          data: $("#addNewEduForm").serialize(),
       success: function(data) {
                }
        });
    }
});
</script>

答案 1 :(得分:2)

我可以看到您尝试使用AJAX提交表单?查看serialize函数。

$('#addedu').click(function(e) {
    e.preventDefault();
    var form = $('form');

    if (form.valid()) { //if you use validation
        $.ajax({
            url: form.attr('action'),
            type: form.attr('method'),
            data: form.serialize(),
            success: function(r) {

            }
        });
    }
});

答案 2 :(得分:0)

您可以使用getElementById获取您的值,然后发送您的操作:

$(document).ready(function () {
    var select = document.getElementById('...');
    $.ajax({
        type: "get", 
        url: "get_street_name", 
        data: { a: select },
        success: function (data) {
            $('#result').html(data);
        }
    });
}