控制器总是收到空参数 [英] Controller always received null arguments

查看:98
本文介绍了控制器总是收到空参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的联系人控制器操作始终收到一个空对象。我错过了什么?



控制器



(我在mail.Body任务中添加了断点,并且整个消息对象为null)

  [HttpPost] 
public ActionResult Contact(ContactMessage message)
{
var mail = new MailMessage();
var client = new SmtpClient(localhost);
mail.From = new MailAddress(************);
mail.To.Add(new MailAddress(****************));
mail.Subject =来自*************.com的新消息;
mail.Body = message.Message;

client.Send(mail);

返回Json(new {success = true});
}



模型



  public class ContactMessage 
{
[Required]
[PlaceHolder(john.smith@example.com)]
public string EmailAddress {get;组; }
[必需]
[PlaceHolder(John Smith)]
public string Name {get;组; }
[必需]
[PlaceHolder(我感兴趣...)]
[DataType(DataType.MultilineText)]
public string Message {get;组; }

public bool Delivered {get;组; }

public ContactMessage()
{
this.Delivered = false;
}
}



在视图中触发的javascript



 < script> 
$(document).ready(function(){
$(#contactForm)。submit(function(event){
event.preventDefault();
var $ form = $(this);

if($ form.valid()){
$ .ajax({
url:/ Contact,
type :POST,
数据:{名称:'繁荣',EmailAddress:'pow',消息:'繁荣热潮'}
})。成功(功能(响应){
if(response.success){
alert(success);
} else {
alert(not success);
}
})。fail (function(){
alert(fail);
});
}
});
});
< / script>

我也试过用Postman发送数据 - 但这似乎也导致了一个空对象。 / p>






更新



我做了一些改动(和进展)但我仍然有问题。



关于错误命名的 Paul Zahra的建议,现在ContactData中的类(不是ContactMessage)



通过关注 ekad的回答,消息对象不再完全为null,而是具有null Name EmailAddress ,消息属性。



我还添加了contentType属性归功于 ramiramilu的 ekad的答案



更新代码:

  [HttpPost] 
public ActionResult联系人(ContactData数据)
{
var mail = new MailMessage();
var client = new SmtpClient(localhost);
mail.From = new MailAddress(************);
mail.To.Add(new MailAddress(************));
mail.Subject =来自************。com的新消息;
mail.Body = data.Message;

client.Send(mail);

返回Json(new {success = true});
}

< script>
$(document).ready(function(){
$(#contactForm)。submit(function(event){
event.preventDefault();
var $ form = $(this);
var msg = {Name:boom,EmailAddress:pow,消息:boom boom pow};

if($ form.valid ()){
$ .ajax({
url:/ Contact,
type:POST,
data:JSON.stringify({message:msg}) ,
contentType:application / json; charset = utf-8
})。success(function(response){
if(response.success){
alert(成功);
}其他{
提醒(不成功);
}
})。失败(function(){
alert(fail) );
});
}
});
});
< / script>


解决方案

由于消息在控制器动作方法中不是javascript原始类型,在传递参数时需要使用 JSON.stringify 。更改您的javascript如下:

 < script> 
$(document).ready(function(){
$(#contactForm)。submit(function(event){
event.preventDefault();
var $ form = $(this);
var msg = {Name:boom,EmailAddress:pow,消息:boom boom pow};

if($ form.valid ()){
$ .ajax({
url:/ Contact,
类型:POST,
数据:JSON.stringify({data:msg}) ,
contentType:application / json; charset = utf-8
})。success(function(response){
if(response.success){
alert(成功);
}其他{
提醒(不成功);
}
})。失败(function(){
alert(fail) );
});
}
});
});
< / script>

此外,参数名称( data )从上面的代码中 JSON.stringify 方法:

  JSON.stringify ({data:msg})

必须与参数名称联系控制器中的操作方法:

  public ActionResult Contact(ContactData data)


My contact controller action always receives a null object. What am I missing?

The Controller

(I have added breakpoints at the mail.Body assignment, and the entire message object is null)

[HttpPost]
public ActionResult Contact(ContactMessage message)
{
    var mail = new MailMessage();
    var client = new SmtpClient("localhost");
    mail.From = new MailAddress("************");
    mail.To.Add(new MailAddress("****************"));
    mail.Subject = "New Message from *************.com";
    mail.Body = message.Message;

    client.Send(mail);

    return Json(new { success = true });
}

The Model

public class ContactMessage
{
    [Required]
    [PlaceHolder("john.smith@example.com")]
    public string EmailAddress { get; set; }
    [Required]
    [PlaceHolder("John Smith")]
    public string Name { get; set; }
    [Required]
    [PlaceHolder("I am interested in...")]
    [DataType(DataType.MultilineText)]
    public string Message { get; set; }

    public bool Delivered { get; set; }

    public ContactMessage()
    {
        this.Delivered = false;
    }
}

The javascript being fired in the view

<script>
    $(document).ready(function () {
        $("#contactForm").submit(function (event) {
            event.preventDefault();
            var $form = $(this);

            if ($form.valid()) {
                $.ajax({
                    url: "/Contact",
                    type: "POST",
                    data: { Name: 'boom', EmailAddress: 'pow', Message: 'boom boom pow' }
                }).success(function (response) {
                    if (response.success) {
                        alert("success");
                    } else {
                        alert("not success");
                    }
                }).fail(function () {
                    alert("fail");
                });
            }
        });
    });
</script>

I have also tried sending data with Postman - but that also seems to result in a null object.


Update

I have made a few changes (and progress)but am still having issues.

Following Paul Zahra's advice on bad naming, the class in now ContactData (not ContactMessage)

By following ekad's answer, the message object is no longer entirely null, rather, a ContactMessage object with null Name, EmailAddress, and Message properties.

I have also added the contentType property thanks to ramiramilu's and ekad's answers

Updated code:

[HttpPost]
public ActionResult Contact(ContactData data)
{
    var mail = new MailMessage();
    var client = new SmtpClient("localhost");
    mail.From = new MailAddress("************");
    mail.To.Add(new MailAddress("************"));
    mail.Subject = "New Message from ************.com";
    mail.Body = data.Message;

    client.Send(mail);

    return Json(new { success = true });
}

<script>
    $(document).ready(function () {
        $("#contactForm").submit(function (event) {
            event.preventDefault();
            var $form = $(this);
            var msg = { Name: "boom", EmailAddress: "pow", Message: "boom boom pow" };

            if ($form.valid()) {
                $.ajax({
                    url: "/Contact",
                    type: "POST",
                    data: JSON.stringify({ message: msg }),
                    contentType: "application/json; charset=utf-8"
                }).success(function (response) {
                    if (response.success) {
                        alert("success");
                    } else {
                        alert("not success");
                    }
                }).fail(function () {
                    alert("fail");
                });
            }
        });
    });
</script>

解决方案

Since message in the controller action method is not a javascript primitive type, you need to use JSON.stringify when passing the parameters. Change your javascript as below:

<script>
    $(document).ready(function () {
        $("#contactForm").submit(function (event) {
            event.preventDefault();
            var $form = $(this);
            var msg = { Name: "boom", EmailAddress: "pow", Message: "boom boom pow" };

            if ($form.valid()) {
                $.ajax({
                    url: "/Contact",
                    type: "POST",
                    data: JSON.stringify({ data: msg }),
                    contentType: "application/json; charset=utf-8"
                }).success(function (response) {
                    if (response.success) {
                        alert("success");
                    } else {
                        alert("not success");
                    }
                }).fail(function () {
                    alert("fail");
                });
            }
        });
    });
</script>

Also, the parameter name (data) inside JSON.stringify method from the code above:

JSON.stringify({ data: msg })

must be the same as the parameter name of Contact action method in the controller:

public ActionResult Contact(ContactData data)

这篇关于控制器总是收到空参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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