简体   繁体   中英

javascript call MVC Controller parameter always null when object field is private

I use javascript to call controller to process a function. The parameter value (name in summary) is null when the field is set to private. It works when the field is set to public. Is set to public the only way? or there is a better way to do it? thanks in advance.

My object

[DataContract]
public class Summary
{
 [DataMember]
 public int id { private set; get; }
 [DataMember]
 public string name { private set; get; }

 public summary() {}

 public summary(int id, string name)
 {
   id = id;
   name = name;
 }

}

MVC Controller

public ActionResult SetSummary(Summary summary)
 {
    string anme = summary.name; **<-- null if private**
    ...
 }

Javascript

$http.post("MyController/SetSummary", JSON.stringify({
            summary: mySummaryObject}))
        .success(function (data, status, headers, config) {
    ....
    }

yup, it should be public because defaultmodelbinder Maps a browser request to a data object. This class provides a concrete implementation of a model binder.

The DefaultModelBinder class maps the following types of objects to a browser request:

Primitive types, such as String , Double, Decimal , or DateTime objects.

Model classes, such as Person, Address, or Product.

Collections, such as ICollection, IList, or IDictionary.

Source: https://msdn.microsoft.com/en-us/library/system.web.mvc.defaultmodelbinder(v=vs.118).aspx

Hope it was useful kindly let me know your thoughts or feedbacks

Thanks

Karthik

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM