Skip to main content
 首页 » 编程设计

c#之使用ajax将值传递给 Controller

2024年04月30日40xxx_UU

我想使用 ajax 将值从 View 传递到 Controller 。

 <button onclick="addCommentByAjax()" >Save</button> 

My script:

function addCommentByAjax() { 
    $.ajax({ 
        type: "POST", 
        url: '/Survey/DoDetailSurvey', 
 
        data: { 
            choiceId: "1" 
        } 
 
 
}); 
} 

Controller:

 [HttpPost] 
    public ActionResult DoDetailSurvey(SurveyViewModel model, string choiceId) 
    { 
     // 
    } 

but choiceId always null

请您参考如下方法:

改变几件事。

首先为您的按钮分配一个 id 或类。其次删除内联 onclick 函数并使用 ajax click 函数。然后将请求类型指定为 Post。

$('#btnComment').click(function () {        
    var choiceId = $('#YourChoiceId').val(); 
 
    $.ajax({ 
        url: '/Survey/DoDetailSurvey', 
        data: { 'choiceId' : choiceId}, 
        type: "post", 
        cache: false, 
        success: function (response) { 
           //do something with response 
        }, 
        error: function (xhr, ajaxOptions, thrownError) { 
             alert('error occured'); 
        } 
    }); 
}); 

那么你的 Controller 应该是这样的

[HttpPost] 
public ActionResult DoDetailSurvey(string choiceId) 
{ 
     // 
} 

我不知道你是如何填充你的 View 模型的,所以我特意删除了它们并展示了一个工作示例。

如果你想传递 View 模型,你应该像这样构造你的数据对象:

var data = {}; 
data.Property1 = some val; 
data.Property2 = "some val";    
 
$.post('/Survey/DoDetailSurvey', data); 

我假设的 SurveyViewModel 示例结构:

public class SurveyViewModel  
{ 
    public int Property1 { get; set; } 
    public string Property2 { get; set; } 
}