ryan
ryan

Reputation: 71

Ajax send JSON data to a c# model

I’m new to MVC so I’m not sure if this is the correct way of doing this. What I’m trying to do is send some JSON data to my controller via ajax, then to my model, to eventually do something to it. The object I’m sending looks like this before I JSON it on the javascript side

bannerID:undefined
bannerMode:"WIDGET"
heightSettings:"0"
images:Array[2]
toggleArrows:"true"
toggleIndicators:"true"
transitionSpeed:""
widthSettings:"0"

When I JSON it looks like this, when I view it on my controller by replacing widget with string i get this.

 {"bannerMode":"WIDGET","transitionSpeed":"","toggleArrows":"true","toggleIndicators":"true","widthSettings":"0","heightSettings":"0","images":

 [{"id":0,"orderRank":"1","imageLink":"http://localhost:49999/img/admin/banner/example.jpg"},{"id":1,"orderRank":"2"}]}

In the parameters of the controller of my controller I have a widget model.

 public ActionResult Index(widget widgetData){
  return View("~/Views/widgets/_dynamicWidget.cshtml", widgetData);
 }

My widget model looks like this.

public class widget
 {
    public string bannerMode { get; set; }
    public int transitionSpeed { get; set; }
    public bool toggleArrows { get; set; }
    public bool toggleIndicators { get; set; }
    public int widthSettings = 20;
    private string lang;
    private List<WidgetList> images1;

    public widget(string lang, List<WidgetList> images1)
    {
        this.lang = lang;
        this.images1 = images1;
    }

    public int heightSettings{ get; set; }
    public List<ImageList> images { get; set; }
}

    public class ImageList
{
    public int id { get; set; }
    public int orderRank { get; set; }
    public string imageLink { get; set; }
}

I’m guessing the data should be set into the model ? But in my view I’m getting a null error when I try to show this data.

Upvotes: 0

Views: 138

Answers (1)

jfren484
jfren484

Reputation: 1010

Your widget class does not have a public parameterless constructor, so I'm guessing the model binder is failing there.

Upvotes: 1

Related Questions