Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
net mvc,jQuery/JavaScript-将变量(对象)传递给操作方法_Javascript_Jquery_Asp.net Mvc - Fatal编程技术网

net mvc,jQuery/JavaScript-将变量(对象)传递给操作方法

net mvc,jQuery/JavaScript-将变量(对象)传递给操作方法,javascript,jquery,asp.net-mvc,Javascript,Jquery,Asp.net Mvc,我在asp.net局部视图中执行jQuery$.ajax函数,以调用控制器操作方法来设置会话变量 我将创建的var对象字符串化 如果我使用: contentType: "application/json", 它不进入控制器操作方法,而是 success: function 返回警报 我的控制台日志显示对象属性具有值 为什么不进入控制器操作方法? 在此场景中,如果我使用: contentType: "application/x-www-form-urlen

我在asp.net局部视图中执行jQuery$.ajax函数,以调用控制器操作方法来设置会话变量

我将创建的var对象字符串化

如果我使用:

contentType: "application/json",
它不进入控制器操作方法,而是

 success: function
返回警报

我的控制台日志显示对象属性具有值

为什么不进入控制器操作方法?


在此场景中,如果我使用:

contentType: "application/x-www-form-urlencoded; charset=UTF-8",
它确实进入控制器操作方法,但它接收的参数为NULL

然而,我的控制台日志显示对象属性具有值。和

 success: function
返回警报

为什么输入参数为空?


部分观点:

@model GbngWebClient.Models.LikeOrDislikeVM

<style>
.fa {
    cursor: pointer;
    user-select: none;
}

    .fa:hover {
        color: blue;
    }

/* I added. */
.my-size {
    font-size: 20px;
}

.my-button {
    border: none;
    padding: 8px 10px;
     /* To make the buttons stay on the same line. */
    float: left;
    font-size: 16px;
    margin: 4px 2px;
    background-color: white;
}
</style>

<div class="row">
<div>
    <button class="blogLike my-button fa fa-thumbs-up"><span class="my-size, likeCount"> : @Model.LikeCount </span></button>
    <button class="blogDisLike my-button fa fa-thumbs-down"><span class="my-size, dislikeCount"> : @Model.DisLikeCount</span></button>
</div>
</div>

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")
@Styles.Render("~/Content/css")

<script type="text/javascript">
$(document).ready(function () {
    // For testing:
    console.log('Here at ready. ');

    // JavaScript needs it as 'false'. So using these 'const' to convert them.
    const False = false, True = true;

    // Set the disabled attributes and color.
    SetLike(@Model.LikeDisabled);
    SetDisLike(@Model.DisLikeDisabled);

    // Create the variable in the image of the LikeOrDislikeVM view model.
    var holdLikeOrDislikeVM = {
        BlogId : @Model.BlogId,
        UserId: @Model.UserId,
        LikeCount: @Model.LikeCount,
        DisLikeCount: @Model.DisLikeCount,
        LikeDisabled: @Model.LikeDisabled,
        DisLikeDisabled: @Model.DisLikeDisabled,
    };

    console.log("hold: " + holdLikeOrDislikeVM.BlogId);
    console.log("hold: " + holdLikeOrDislikeVM.UserId);
    console.log("hold: " + holdLikeOrDislikeVM.LikeCount);
    console.log("hold: " + holdLikeOrDislikeVM.DisLikeCount);
    console.log("hold: " + holdLikeOrDislikeVM.LikeDisabled);
    console.log("hold: " + holdLikeOrDislikeVM.DisLikeDisabled);

    $.ajax({
        type: 'POST',
        url: '@Url.Action("SetModelSessionVar", "BlogPublished")',
        data: { likeOrDislikeVM: JSON.stringify(holdLikeOrDislikeVM) },
        //contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        contentType: "application/json",
        success: function (response) {
            alert("Success. Response: " + response);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert("Critical Error: something is wrong in the call to SetModelSessionVar! Status: " + xhr.status + ". Error: " + thrownError.toString() + ". Response Text: " + xhr.responseText);
        }
    })
                  

    //--------------------------------------------------------------------------------------
    // Set the disabled attribute to true or false.
    //--------------------------------------------------------------------------------------
    function SetLike(disabledSwitch) {
        // For testing:
        console.log('Here at Setlike. ' + disabledSwitch);

        $(".blogLike").attr('disabled', disabledSwitch);

        if (disabledSwitch == true )
        {
            // Show by color that it was previously liked.
            $(".blogLike").css('color', 'green');
        }

        if (disabledSwitch == false)
        {
            // Show by color that it can be clicked.
            $(".blogLike").css('color', 'black');
        }
    }

    //--------------------------------------------------------------------------------------
     // Set the disabled attribute to true or false.
    //--------------------------------------------------------------------------------------
    function SetDisLike(disabledSwitch) {
        // For testing:
        console.log('Here at SetDisLike. ' + disabledSwitch);

        $(".blogDisLike").attr('disabled', disabledSwitch);

        if (disabledSwitch == true)
        {
            // Show by color that it was previously disliked.
            $(".blogDisLike").css('color', 'green');
        }

        if (disabledSwitch == false)
        {
          // Show by color that it can be clicked.
            $(".blogDisLike").css('color', 'black');
        }
    }
});
</script>

控制器操作方法:

[HttpPost]
public void SetModelSessionVar(LikeOrDislikeVM likeOrDislikeVM)
{
   // Sets a model session variable according to the argument passed in.
   Session["likeOrDislikeVM"] = likeOrDislikeVM;
}

根据与freedomn-m的讨论,我发现:

对于控制器动作方法:

[HttpPost]
public void SetModelSessionVar(string likeOrDislikeVM)
{
   Session["likeOrDislikeVM"] = likeOrDislikeVM;
}
[HttpPost]
public void SetModelSessionVar(LikeOrDislikeVM likeOrDislikeVM)
{
   Session["likeOrDislikeVM"] = likeOrDislikeVM;
}
这是唯一有效的1(进入控制器方法时为:{“BlogId”:40,“UserId”:3,“LikeCount”:0,“DisLikeCount”:1,“LikeDisabled”:false,“DisLikeDisabled”:true}):

不工作(进入控制器方法时为:null):

不工作(进入控制器方法时为:null):

不工作(不进入控制器方法,控制台中未显示任何内容):


现在,控制器动作方法如下:

[HttpPost]
public void SetModelSessionVar(string likeOrDislikeVM)
{
   Session["likeOrDislikeVM"] = likeOrDislikeVM;
}
[HttpPost]
public void SetModelSessionVar(LikeOrDislikeVM likeOrDislikeVM)
{
   Session["likeOrDislikeVM"] = likeOrDislikeVM;
}
这是唯一有效的1(进入控制器方法时为:{模型的图像-这是我想要的,而不是上面的字符串):

注意:我必须从这个局部视图中定义的视图模型创建一个JavaScript对象,因为我似乎无法将该视图模型传递给控制器方法。不知道为什么。我不明白为什么我不能使用视图模型

使用此局部视图中定义的视图模型传递给控制器方法: 不工作(进入控制器方法时为:null):

使用此局部视图中定义的视图模型传递给控制器方法: 不工作(未进入控制器,控制台显示:未定义GbngWebClient引用错误:未定义GbngWebClient):


如果您
JSON.stringify
,那么您的操作参数将需要是
public void SetModelSessionVar(string likeOrDislikeVM)
-事实并非如此,因此它与参数不匹配,因此您会得到
null
确定。我更改了操作方法签名。如果我更改为:contentType:“application/x-www-form-urlencoded;charset=UTF-8”的形式为:{“BlogId”:40,“UserId”:3,“LikeCount”:0,“DisLikeCount”:1,“LikeDisabled”:false,“DisLikeDisabled”:true}。但如果使用contentType:“application/json”,则无法到达控制器。根据本文,参数可以定义为类模型,contentType可以是:“请参阅:该答案与您的答案之间的区别在于,它们在“根”处传递每个参数,而您有一个额外的参数名:
data:{likeOrDislikeVM:json.stringify(holdLikeOrDislikeVM)},
应该是
data:json.stringify(holdLikeOrDislikeVM),
然后模型绑定器将js名称与您的模型名称相匹配。这篇文章也令人困惑,因为它说您“需要使用json.stringify”-您不需要,但如果您不需要,那么就不要使用
应用程序/json
-这两者结合在一起。这也是对web api的回答,而不是有效的mvc稍有不同。freedomn-m,我尝试了您的建议,并在上面添加了我的发现。请参阅:通过与freedomn-m的讨论,我发现:
 $.ajax({
     type: 'POST',
     url: '@Url.Action("SetModelSessionVar", "BlogPublished")',
     data: JSON.stringify(holdLikeOrDislikeVM),
     contentType: "application/x-www-form-urlencoded; charset=UTF-8",
     error: function (xhr, ajaxOptions, thrownError) {
         alert("Critical Error: something");
     }
 })
 $.ajax({
     type: 'POST',
     url: '@Url.Action("SetModelSessionVar", "BlogPublished")',
     data: { likeOrDislikeVM: JSON.stringify(holdLikeOrDislikeVM)},
     contentType: "application/json",
     error: function (xhr, ajaxOptions, thrownError) {
         alert("Critical Error: something");
     }
 })
[HttpPost]
public void SetModelSessionVar(LikeOrDislikeVM likeOrDislikeVM)
{
   Session["likeOrDislikeVM"] = likeOrDislikeVM;
}
 $.ajax({
     type: 'POST',
     url: '@Url.Action("SetModelSessionVar", "BlogPublished")',
     data: { likeOrDislikeVM: holdLikeOrDislikeVM },
     contentType: "application/x-www-form-urlencoded; charset=UTF-8",
     error: function (xhr, ajaxOptions, thrownError) {
         alert("Critical Error: something");
     }
 })
 $.ajax({
     type: 'POST',
     url: '@Url.Action("SetModelSessionVar", "BlogPublished")',
     data: { likeOrDislikeVM: '@Model' },
     contentType: "application/x-www-form-urlencoded; charset=UTF-8",
     error: function (xhr, ajaxOptions, thrownError) {
         alert("Critical Error: something");
     }
 }) 
 $.ajax({
     type: 'POST',
     url: '@Url.Action("SetModelSessionVar", "BlogPublished")',
     data: { likeOrDislikeVM: @Model},
     contentType: "application/x-www-form-urlencoded; charset=UTF-8",
     error: function (xhr, ajaxOptions, thrownError) {
         alert("Critical Error: something");
     }
 })