如何将表单数据转换/获取到JSON对象

时间:2013-05-02 06:55:16

标签: jquery asp.net-mvc json

  

我以json字符串格式获取Form数据但无法绑定它   与模型对象

     

我的观点:

           <div class="GenderaMale float_lt">
            </div>
            <div class="float_lt">@Html.RadioButtonFor(m => m.PersonalDetails.BasicDetails.Gender, "male", new { @style = "margin:10px;margin-top:15px;", id = "malegender" })
            </div>
            <div class="GenderaFemale float_lt" style="margin-left: 30px;">
            </div>
            <div class="float_lt">@Html.RadioButtonFor(m => m.PersonalDetails.BasicDetails.Gender, "Female", new { @style = "margin:10px;margin-top:15px;", id = "femalegender" })
            </div>
            <span class="float_lt" style="margin-right: 15px;
            margin-top: 5px;">Amount</span>
            <div class="rupee" style="float: left">
            </div>
            @Html.TextBoxFor(m => m.Amount, new { @class = "trackwidthtxt float_lt" })

<script type="text/javascript">

        $.fn.serializeObject = function () {
            var o = {};
            var a = this.serializeArray();
            $.each(a, function () {
                if (o[this.name] !== undefined) {
                    if (!o[this.name].push) {
                        o[this.name] = [o[this.name]];
                    }
                    o[this.name].push(this.value || '');
                } else {
                    o[this.name] = this.value || '';
                }
            });
            return o;
        };

        $("#calculateNow").click(function () {

            var viewmodel = $('#CalculateNowForm').serializeObject();
            alert(viewmodel);

            var data = JSON.stringify($('form').serializeObject())
            alert(data);
            var Parameters = '{"leadViewModel":' + data + '}';
            alert(Parameters);
            Events.OpenPopup(ApplicationRoot + '/Calculator/CalculateNow', '', 600, 750, "middle", "#E7F0F5", Parameters);

        });

    </script>
  

这是我的模特:

public partial class LeadViewModel 
{
    public string Amount{ get; set; }
    public PersonalDetailsViewModel PersonalDetails{ get; set; }
}

public partial class PersonalDetailsViewModel 
{
    public BasicDetailsViewModel BasicDetails{ get; set; }
}
public partial class BasicDetailsViewModel 
{
    public string Gender{ get; set; }
}
  

这是我的控制器:

[HttpPost]
        public ActionResult CalculateNow(LeadViewModel leadViewModel)
        {
            LeadViewModel leadmodel = leadViewModel;
            return PartialView("ConfirmToCalculate",leadmodel);
        }

请仔细检查我的Jquery代码尝试..我在控制器方法参数中得到空值,即在leadViewModel上。请帮助我.. !!!

1 个答案:

答案 0 :(得分:0)

只需传递序列化数据而不创建Parameters。模型绑定会将表单值映射到控制器方法的LeadViewModel对象。