数据已保存,但发布请求失败并给出服务器错误

时间:2017-10-11 18:21:47

标签: javascript jquery asp.net-mvc

我尝试通过动作控制器动作方法保存字段,返回不同的视图。但是没有做到这一点:我的Jquery代码是:

$("#btnAdd").click(function () {
    var Product = {
        name: $("#txtProductName").val(),
        color: $("#ddlColor option:selected").val(),
        gage: $("#ddlGage option:selected").val(),
        rate: $("#txtrate").val()
    };
    $.ajax({
    });
    $.post("ProductTable", { Pro: JSON.stringify(Product) }, function (data) {
        $("#RightDiv").html(data);
        alert(data);
    });
});

和我的控制器操作方法在同一控制器上返回不同的视图:

public ActionResult ProductTable()
{
        Product product = new Product();
        JavaScriptSerializer serializer = new JavaScriptSerializer();
        product = serializer.Deserialize<Product>(Request.Form["Pro"]);
        productDB.addProduct(product);
        productManager.productTable = productDB.getAllProducts();
        return View(productManager);
}

浏览器给我错误:

HTTP500: SERVER ERROR - The server encountered an unexpected condition that prevented it from fulfilling the request.
(XHR)POST - http://localhost:59008/Product/ProductTable

1 个答案:

答案 0 :(得分:0)

如果您正在使用MVC,它应该为您处理序列化/反序列化。您只需要确保发送的对象与您在MVC控制器操作参数中声明的对象匹配。

客户端

// Suggestions:
//   * use camelCase for javascript variables and functions
//   * jQuery .val() on selects should give you the selected value
//   * always use fully qualified Url generated by Html.Helper

$("#btnAdd").click(function () {
    var product = {
        name: $("#txtProductName").val(),
        color: $("#ddlColor").val(),
        gage: $("#ddlGage").val(),
        rate: $("#txtrate").val()
    };

    var createUrl = '@Url.Action("create", "product", new { area = "" })';

    $.post(createUrl, product, function (response) {
        $("#RightDiv").html(response);
        alert(response);
    });
});

服务器侧

// Suggestions:
//   * NEVER send your domain model back to the page! You should create 
//     a ViewModel to just include what you want to show the users

[HttpPost]
public ActionResult Create(CreateProductViewModel model)
{
    ...

    productDB.addProduct(new Product {
        Name = model.Name,
        Color = model.Color,
        Gage = model.Gage,
        Rate = model.Rate,
        // And other stuff like
        // CreatedBy = User.Identity.Name
    });

    // This looks weird to me too!
    productManager.productTable = productDB.getAllProducts();

    return View(productManager);
}

ViewModel

public class CreateProductViewModel
{
    public string Name { get; set; }
    public int Color { get; set; }
    public int Gage { get; set; }
    public double Rate { get; set; }
}