从视图中传递模型使用jQuery阿贾克斯到控制器 [英] Passing Model from view to controller with Jquery Ajax

查看:97
本文介绍了从视图中传递模型使用jQuery阿贾克斯到控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试从视图通过我的模型值通过使用Ajax控制器 JQuery的。在我的控制器模型如图

控制器已经从阿贾克斯方法调用,但问题是对象控制器显示为

这是模型的结构简单:

 公共类发票
{
    公共发票(InvoiceHeader invHeader,列表与LT; InvoiceItems> InvItmem)    {
        this.invHeader = invHeader;
        this.InvItmem = InvItmem;
    }    公共InvoiceHeader invHeader {搞定;私人集; }
    公开名单< InvoiceItems> InvItmem {搞定;私人集; }}

这是控制器的结构:

  [HttpPost]
公众的ActionResult InsertItems(列表<发票和GT;发票)
{
    //列表< InvoiceItems> ASD =新的List< InvoiceItems>();
    // ASD =发票()。    返回JSON(真,JsonRequestBehavior.AllowGet);
}

这是查看:

  @model BeetaTechModel.Invoice@ {
    ViewBag.Title =指数;
    VAR VAL = Json.En code(模型);
}< H2>指数< / H>    <脚本类型=文/ JavaScript的>
        $(文件)。就绪(函数(){            $(#btnSubmit按钮)。点击(函数(){                // VAR VAL = Json.En code(模型);                VAR检查= @ Html.Raw(VAL);                $阿贾克斯({
                    输入:POST,
                    网址:发票/ InsertItems
                    数据:{信息:'+ JSON.stringify(检查)+'}',
                    的contentType:应用/ JSON的;字符集= UTF-8,
                    数据类型:JSON
                    成功:功能(数据){
                        警报(数据);
                    }
                });
            });
        });
    < / SCRIPT>@ {Html.RenderPartial(InvoiceHeader,Model.invHeader);}@ {Html.RenderPartial(InvoiceItems,M​​odel.InvItmem);}<输入类型=提交ID =btnSubmit按钮值=登录/>


解决方案

您有4个问题与code。


  • 第一个是在你的AJAX调用它必须是这样的:

      $。阿贾克斯({
        网址:'发票/ InsertItems',
        输入:POST,
        数据:JSON.stringify(检查),
        的contentType:应用/ JSON的;字符集= UTF-8,
        成功:功能(数据){
            警报(数据);
        }
    });


  • 第二个问题是,你订阅了一个提交按钮的。点击事件,而不取消该按钮的默认操作。因此,如果这个按钮是一个形式里面,当你点击它时,浏览器将发布的形式向服务器和重定向客场形式没有留下时刻为您的AJAX调用执行过的动作。因此,请确保您要取消按钮的默认操作:

      $(#btnSubmit按钮)。点击(函数(五){
        亦即preventDefault();    ...您的AJAX调用来这里
    });


  • 第三个问题是,你的发票模型没有一个默认的(无参数)构造函数这意味着你不能没有使用它作为参数传递给控制器​​动作编写自定义模型绑定,因为默认的模型绑定不知道如何进行实例化。


  • 和第四个问题是,无论是 invHeader InvItmem 你的<$ C $的性质C>发票模式不具有公共setter方法​​这意味着JSON序列化将无法设置它们的值。因此,请确保您有固定的发票型号:

     公共类发票
    {
        公共InvoiceHeader InvHeader {搞定;组; }
        公开名单&LT; InvoiceItems&GT; InvItmem {搞定;组; }
    }


I'm try to pass my model values from View to Controller by using ajax JQuery. In my controller that model is shown as null.

Controller already called from ajax method, but the problem is object in the controller is showing as null.

This is Simple structure of model:

public class Invoice
{
    public Invoice(InvoiceHeader invHeader, List<InvoiceItems> InvItmem)

    {
        this.invHeader = invHeader;
        this.InvItmem = InvItmem;
    }

    public InvoiceHeader invHeader { get; private set; }
    public List<InvoiceItems> InvItmem { get; private set; }

}

This is structure of Controller:

[HttpPost]
public ActionResult InsertItems(List<Invoice> invoice)
{
    //List<InvoiceItems> asd = new List<InvoiceItems>();
    //asd = invoice.();

    return Json(true, JsonRequestBehavior.AllowGet);
}

This is View:

@model BeetaTechModel.Invoice

@{
    ViewBag.Title = "Index";
    var val = Json.Encode(Model);
}

<h2>Index</h2>

    <script type="text/javascript"> 
        $(document).ready(function () {

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

                // var val = Json.Encode(Model);

                var check = @Html.Raw(val);

                $.ajax({
                    type: 'POST',
                    url: "Invoice/InsertItems",
                    data: '{info:' + JSON.stringify(check) + '}' ,
                    contentType: 'application/json; charset=utf-8',
                    dataType: "json",
                    success: function (data) {
                        alert(data);        
                    }
                });
            });
        });
    </script>

@{Html.RenderPartial("InvoiceHeader", Model.invHeader);}

@{Html.RenderPartial("InvoiceItems", Model.InvItmem);}        

<input type="submit" id="btnSubmit" value="Log In" />

解决方案

You have 4 issues with your code.

  • The first one is in your AJAX call which must look like this:

    $.ajax({
        url: 'Invoice/InsertItems',
        type: 'POST',
        data: JSON.stringify(check),
        contentType: 'application/json; charset=utf-8',
        success: function (data) {
            alert(data);
        }
    });
    

  • The second issue is that you subscribed to the .click event of a submit button without canceling the default action of this button. So if this button is inside a form, when you click it, the browser will POST the form to the server and redirect away to the action of the form leaving no time for your AJAX call to ever execute. So make sure you are canceling the default action of the button:

    $("#btnSubmit").click(function (e) {
        e.preventDefault();
    
        ... your AJAX call comes here
    });
    

  • The third issue is that your Invoice model doesn't have a default (parameterless) constructor meaning that you cannot use it as argument to a controller action without writing a custom model binder because the default model binder wouldn't know how to instantiate it.

  • And the fourth issue is that both the invHeader and InvItmem properties of your Invoice model do not have public setters meaning that the JSON serializer will be unable to set their values. So make sure you have fixed your Invoice model:

    public class Invoice
    {
        public InvoiceHeader InvHeader { get; set; }
        public List<InvoiceItems> InvItmem { get; set; }
    }
    

这篇关于从视图中传递模型使用jQuery阿贾克斯到控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆