2

I'm trying to send a TypeScript class with the jQuery post method. And everything is working well, but there is one point I'm trying to fix.

Lets say i got the model below.

export class TestModel{
    private id: string;
    private username: string;

    constructor(id: string, username: string) {
        this.id= loginName;
        this.username= password;
    }

    IsValid(): boolean {
        return true;
    }
}

And to post it i got this function:

var testModel = new TestModel("test1", "test2");
    $.ajax({
         url: "MyUrl",
         type: "POST",
         data: testModel,
     });

When I look to the network request the folowing information is post:

id: test1
username: test2
IsValid: true

The only things i want to post is the id and username, the IsValid method is only to validate this model, like are all fields filled in, when it's an email field check an email filled in etc.

So my question is, what is the solution to only send the id and username, without any other functions? (if this is possible ofcourse :)).

Thanks for your help, Stefan

1 Answer 1

1

the IsValid is in the javascript object. if you want to remove it from the object (but you won't have access after) you can delete it like that (javascript code):

delete['IsValid'];

The best way is to manually pass the parameter you want to your ajax query.

Javascript (converted from typescript) :

var TestModel = (function () {
    function TestModel(id, username) {
        // I've corrected this part
        this.id = id; 
        this.username = username;
    }
    TestModel.prototype.IsValid = function () {
        return true;
    };
    return TestModel;
})();

Ajax query :

var testModel = new TestModel("test1", "test2");

$.ajax({
     url: "",
     type: "POST",
     data: { id:testModel.id, username:testModel.username } // Access property with <object>.<property>
});

You will see id=test1&username=test2 in your POST data

TypeScript code :

export class TestModel{
    private id: string;
    private username: string;

    constructor(id: string, username: string) {
        this.id = id;
        this.username = username;
    }

    IsValid(): boolean {
        return true;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.