Asp.net mvc jquery ajax post返回null

时间:2014-12-10 14:29:43

标签: jquery ajax asp.net-mvc-4

我是stackoverflow的新手,很抱歉发布的语法。 我的问题是没有发布任何值或模型没有获得任何值 这是我的控制器功能:

[HttpPost]
public JsonResult SendToStoresPost(tempStoreProduct temp)
{
    ViewBag.returenValue = temp.quantity.ToString();
    return Json(ViewBag.returenValue);
}

以下是模型:

public class tempStoreProduct
{
    public int productid;
    public int quantity;
    public int store;        
}

以下是ajax帖子的jquery:

function send(productid)
{
    var quantity = $('#amount-'+productid).val();
    var store = $('#stores').val();
    var temp = {
        productid: productid,
        quantity: quantity,
        store: store
    }
    $.ajax({
        url: "SendToStoresPost", //The url where the server req would we made.
        type: "POST", //The type which you want to use: GET/POST
        data: temp,
        dataType: "JSON", //Return data type (what we expect).
        beforeSend:function(){
            $('#ico-'+productid).html('loading');
        },
        success: function(data) {
            $('#ico-'+productid).html(data);
        }
    });
}

坚持了一段时间。

3 个答案:

答案 0 :(得分:0)

我认为你的ajax电话中的网址有什么不对。我建议您使用@ Url.Action并在渲染视图时将其放在javascript变量中:

<script type="text/javascript">
   var urlSendToStoresPost = '(@Url.Action("SendToStoresPost","ControllerName"))';
</script>

我不能100%确定上面的语法。

稍后在你的ajax电话中:

$.ajax({
    url: urlSendToStoresPost, //The url where the server req would we made.
    type: "POST", //The type which you want to use: GET/POST
    data: temp,
    dataType: "JSON", //Return data type (what we expect).
    beforeSend:function(){
        $('#ico-'+productid).html('loading');
    },
    success: function(data) {
        $('#ico-'+productid).html(data);
    }
});

答案 1 :(得分:0)

function send(productid)
{
    var quantity = $('#amount-'+productid).val();
    var store = $('#stores').val();
    var temp = {
        productid: productid,
        quantity: quantity,
        store: store
    }
    $.ajax({
        url: "SendToStoresPost", //The url where the server req would we made.
        type: "POST", //The type which you want to use: GET/POST
        data: temp,
        dataType: "JSON", //Return data type (what we expect).
        contentType: "application/json",
        beforeSend:function(){
            $('#ico-'+productid).html('loading');
        },
        success: function(data) {
            $('#ico-'+productid).html(data);
        }
    });
}

答案 2 :(得分:0)

您的模型属性没有getter和setter(它们是字段!),因此在发布时无法设置属性。将模型更改为

public class tempStoreProduct
{
  public int productid { get; set; }
  public int quantity { get; set; }
  public int store { get; set; }       
}

另外,如果你真的有

var quantity = $('#amount-'+productid).val();

意味着你拥有id="amount-1"id="amount-2"等控件,你需要重新思考你在做什么,并学习使用强类型助手根据你的模型构建html。

注意,在POST方法中为视图包分配属性然后再次访问它有点无意义(就像调用.ToString()一样) - 它可以只是

[HttpPost]
public JsonResult SendToStoresPost(tempStoreProduct temp)
{
  return Json(temp.quantity);
}

虽然我认为这不是真正的代码(为什么将值传递给服务器只返回完全相同的值)