为什么MVC控制器没有接收到具有正确值的模型对象?

时间:2014-03-05 21:06:22

标签: asp.net-mvc asp.net-mvc-3

我看到我的控制器操作正确获取了id参数。该网址在执行操作时是正确的。

即使我从js函数发送完全填充的模型对象,模型也将所有字段都设置为null。

为什么控制器没有使用我正在通过的值获得模型对象?

发送请求的JS函数:

function updateSettings(){
        //read values from the form                
                var name = $name_from_page;
                var msg = $msg_from_page;
                var abt = $abt_from_page;
                var bg = $BG_from_page;

                var webLinks = [];
                var text = "";
                var url = "";
                for(var i=1; i <= 4; i++)
                {
                    text = $text_from_page;
                    url = $url_from_page;                             
                webLinks.push({ Text: text, URL: url });
                }      
            var allowLikes = $allowLikes_from_page;
                var allowComments = $allowComments_from_page;

                var model = {};
                model.Title = name;
                model.Message = msg;
                model.About = abt;
                model.BannerBGColor = bg;
                model.BannerBGImage = "";
                model.AllowComments = allowLikes;
                model.AllowLikes = allowComments;
                model.WebLinks = webLinks;

            //using js library to send request
                Requestor
                .post("Update_Page_URL")
                .addParams({ model: model })
                .send();
}

这是传递给控制器​​操作的内容:

{"Title":"Bob","Message":"Message","About":"About Bob","BannerBGColor":"#eee;","BannerBGImage":"","AllowComments":true,"AllowLikes":false,"WebLinks":[{"Text":"abc","URL":"www.abc.com"}]}

Controlelr行动:

[HttpPost]
public ActionResult UpdateSettings(string id, PageModel model)
{
  //read model and update database
  //model object has all fields null and the 2 booleans are false <<== ISSUE
}

控制器操作中使用的模型:

public class PageModel
    {
        public string UserName { get; set; }

        public string Title { get; set; }

        public string Message { get; set; }

        public string About { get; set; }

        public string BannerBGColor { get; set; }

        public string BannerBGImage { get; set; }

        public bool AllowComments { get; set; }

        public bool AllowLikes { get; set; }

        public List<WebLink> WebLinks { get; set; }        

    }

1 个答案:

答案 0 :(得分:0)

您的操作期待JSON,但您也有一个字符串ID参数。将id移动到JSON中并记住设置内容类型:

dataType: 'json',
contentType: 'application/json',