使用非侵入式JavaScript,参数不为空,但它的值是 [英] Using unobtrusive JavaScript, parameter isn't null, but its values are

查看:108
本文介绍了使用非侵入式JavaScript,参数不为空,但它的值是的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是工作时,我的JavaScript是在同一页我CSHTML文件:

 函数SaveEntity(){
    //更多code在这里
    警报(entity.FirstName); //这表明实体的属性有值
    .post的$('/主页/保存,{实体:实体},SaveComplete);
}

这code现在是在一个单独的Index.js文件。在我的控制器,实体参数不是null,但其所有的价值都是。为什么现在发生?

控制器签名:

 公众的ActionResult保存(实体实体)
{//此处的方法}

编辑 - 提琴手截图

修改

这是实体类,由实体框架生成的:

 公共部分类实体
{
    公共实体()
    {
        this.Contacts =新的HashSet<联系与GT;();
    }    公众诠释ENTITYID {搞定;组; }
    公共字符串名字{获得;组; }
    公共字符串名字{获得;组; }
    公共字符串地址{搞定;组; }
    公共字符串城{搞定;组; }
    公共字符串状态{搞定;组; }
    公共字符串邮编code {搞定;组; }
    公共字符串公司{搞定;组; }
    公共字符串LastModifiedUser {搞定;组; }
    公众可空<&System.DateTime的GT; LastModifiedTime {搞定;组; }
    公共字符串注{搞定;组; }    公共虚拟的ICollection<联系与GT;联系方式{搞定;组; }
}

修改

全Index.js,拥有完整SaveEntity()方法:

  VAR _currentEntities;    $(函数(){
        //隐藏ID列(列1)
        $('#tableContacts)。dataTable的({
            aoColumnDefs:[
                {bSearchable:假的,bVisible:假的,aTargets:[0]}
            ]
            bLengthChange:假的,//不显示的记录,每页显示多少
            bFilter:假的,//不显示在搜索/过滤箱
            iDisplayLength:5
        });        $('#waitImage')隐藏()。
        //显示的英文字母,一个链接调用GetEntries()为他们每个人。
        对于(VAR我= 65; I< = 90;我++){
            $('#headerAlphabet')追加('< A HREF = \\#\\的onclick = \\GetEntries(\\''
                + String.fromChar code(1)+\\')\\>'
                + String.fromChar code(1)+'< / A> ');
        }
    });            功能GetEntries(firstLetter){
                // code在这里
            }            功能EntriesReceived(实体){
                // code在这里
            }            功能DisplayPerson(ENTITYID){
                // code在这里
            }        功能SaveEntity(){
            //取得我们的实体
            VAR实体;
            对于(VAR I = 0; I< _currentEntities.length;我++){
                如果(_currentEntities [Ⅰ] .EntityId == $('#txtEntityId')。VAL()){
                    实体= _currentEntities [I]
                    打破;
                }
            }            entity.FirstName = $('#txtFirstName)VAL()。
            entity.LastName = $('#txtLastName)VAL()。
            entity.Address = $('#txtAddress)VAL()。
            。entity.City = $('#txtCity)VAL();
            。entity.State = $('#txtState)VAL();
            entity.Zip code = $('#txtZip code')VAL()。
            entity.Company = $('#txtCompany)VAL()。
            entity.Notes = $('#txtNotes)VAL()。            警报(entity.FirstName);            .post的$('/主页/保存,{实体:实体},SaveComplete);
        }            功能SaveComplete(saveStatus){
                警报(saveStatus);
            }            功能CancelChanges(){
                警报('取消将在这里完成。');
            }


解决方案

首先,在做任何一种AJAX提交的时候,你想看看在HTTP调试器的实际要求,如提琴手。你想看看它的实际发布你认为它是值。这将帮助你找出问题是否在你的JavaScript,或者在服务器上。现在,你不知道。

请参阅:和<一个href=\"http://books.google.com/books?id=JP1RbrxVti4C&pg=PT656&lpg=PT656&dq=using%20fiddler%20to%20debug%20ajax%20mvc&source=bl&ots=n_1V4nCC0S&sig=m54fUyvVQjIlwInVk8sP_QbXDb4&hl=en&sa=X&ei=8nUxUauvKoL49QTDmIDABw&ved=0CG8Q6AEwBw\"相对=nofollow>这

其次,你应该张贴您的服务器端实体定义。

编辑:

这似乎是与jQuery的默认对象序列化,它使用了括号标记,这将不使用默认的模型绑定的工作方式,有问题。你必须使用传统的:戴夫提到真正的参数

更多关于这里。下面将解决您的问题。与真正的参数一起使用,将迫使传统的序列化时, $。参数方法。

  $。员额('/主页/保存,$ .PARAM(实体,真),SaveComplete);.

This was working when my JavaScript was in the same page as my cshtml file:

function SaveEntity() {
    // more code here
    alert(entity.FirstName);  // this shows that entity's properties have values
    $.post('/Home/Save', { entity: entity }, SaveComplete);
}

That code is now in a separate Index.js file. In my controller, the entity parameter isn't null, but all of its values are. Why would that happen now?

Controller signature:

public ActionResult Save(Entity entity)
{ // method here }

Edit - Fiddler Screenshot

Edit

This is the Entity class, generated by Entity Framework:

public partial class Entity
{
    public Entity()
    {
        this.Contacts = new HashSet<Contact>();
    }

    public int EntityId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }
    public string ZipCode { get; set; }
    public string Company { get; set; }
    public string LastModifiedUser { get; set; }
    public Nullable<System.DateTime> LastModifiedTime { get; set; }
    public string Notes { get; set; }

    public virtual ICollection<Contact> Contacts { get; set; }
}

Edit

Full Index.js, with the full SaveEntity() method:

var _currentEntities;

    $(function () {
        // Hide the ID column (column 1)
        $('#tableContacts').dataTable({
            "aoColumnDefs": [
                { "bSearchable": false, "bVisible": false, "aTargets": [0] }
            ],
            "bLengthChange": false, // don't show the number of records to show per page
            "bFilter": false,  // don't show the search/filter box
            "iDisplayLength": 5
        });

        $('#waitImage').hide();
        // Show the letters of the alphabet, with a link to call GetEntries() for each of them.
        for (var i = 65; i <= 90; i++) {
            $('#headerAlphabet').append('<a href=\"#\" onclick=\"GetEntries(\''
                + String.fromCharCode(i) + '\')\">'
                + String.fromCharCode(i) + '</a> ');
        }
    });

            function GetEntries(firstLetter) {
                // code here
            }

            function EntriesReceived(entities) {
                // code here
            }

            function DisplayPerson(entityId) {
                // code here
            }

        function SaveEntity() {
            // Grab our entity
            var entity;
            for (var i = 0; i < _currentEntities.length; i++) {
                if (_currentEntities[i].EntityId == $('#txtEntityId').val()) {
                    entity = _currentEntities[i];
                    break;
                }
            }

            entity.FirstName = $('#txtFirstName').val();
            entity.LastName  = $('#txtLastName').val();
            entity.Address   = $('#txtAddress').val();
            entity.City      = $('#txtCity').val();
            entity.State     = $('#txtState').val();
            entity.ZipCode   = $('#txtZipCode').val();
            entity.Company   = $('#txtCompany').val();
            entity.Notes     = $('#txtNotes').val();

            alert(entity.FirstName);

            $.post('/Home/Save', { entity: entity }, SaveComplete);
        }

            function SaveComplete(saveStatus) {
                alert(saveStatus);
            }

            function CancelChanges() {
                alert('Cancel will be done here.');
            }

解决方案

First, when doing any kind of ajax submission, you want to look at the actual request in an Http debugger, like Fiddler. You want to see if it's actually posting the values you think it is. That will help you isolate whether the problem is in your javascript, or on the server. Right now, you don't know.

See: This and This

Second, you should post your server side Entity definition.

EDIT:

This appears to be a problem with the way that jQuery serializes objects by default, which uses the bracket notation, which won't work with the default model binder. You have to use the traditional: true parameter that Dave mentions.

More about that Here. The following will solve your problem. the $.param method when used with the true parameter will force traditional serialization.

$.post('/Home/Save', $.param(entity, true), SaveComplete);. 

这篇关于使用非侵入式JavaScript,参数不为空,但它的值是的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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