【问题标题】:Creating a ViewModel in MVC from Javascript for a Post method从 Javascript 在 MVC 中为 Post 方法创建 ViewModel
【发布时间】:2025-12-07 02:15:02
【问题描述】:

我正在尝试创建部分视图,它是用于创建新 ProductionGoal 模型的提交表单。它使用 ProductionLineViewModel 来创建它。

我的主要问题是如何将该数据传递到我的 CreateNewProductionGoal 控制器方法中。我写了一些粗略的 JS,但我还是 JS 的新手,我不完全确定我在做什么。我使用这个链接作为编写我的 JS 的基础: How to post data from ViewModel into a controller method?

目前,当我按下按钮时,CreateNewProductionGoal 方法不会被调用。我想知道是否需要添加一些东西来实现这一点,或者我是否还有其他错误。

<input id="submit" type="button" class="button" value="Submit" onclick="onClick();">

function onClick() {
    alert("I am an alert box!");

    var Employees = $("#productiongoal-text").data("kendoNumericTextBox").value();
    var ProdLineId = $("#productionLine-dropdown").data("kendoDropDownList").value();
    var ProductionGoalViewModel = { "NumberOfEmployees": Employees, "ProductionLineId": ProdLineId };
    var requestData = {}
    var data = { request: requestData, pgvm: ProductionGoalViewModel }

    $.ajax({
        type: 'post',
        url: "ProductionLine/CreateNewProductionGoal",
        dataType: "json",
        data: data,  //Creating a ProductionGoalViewModel to pass into the CreateNewProductionGoal method
        success: function (data) {
            location = location;  //Refreshes the page on button press
        }
    });

}

[HttpPost]
    public ActionResult CreateNewProductionGoal([DataSourceRequest] DataSourceRequest request, ProductionGoalViewModel pgvm)
    {
        if (pgvm != null && ModelState.IsValid)
        {
            ProductionGoal pg = new ProductionGoal();
            pg.NumberOfEmployees = pgvm.NumberOfEmployees;
            pg.NumberOfUnits = _prodLineService.Find(pgvm.ProductionLineId).UPE * pgvm.NumberOfEmployees;
            pg.ProductionLineId = pgvm.ProductionLineId;
            pg.ProdLine = _prodLineService.Find(pgvm.ProductionLineId);
            pgvm.NumberOfUnits = pg.NumberOfUnits;
            pgvm.Id = pg.Id;
            pgvm.CreatedAt = pg.CreatedAt;
            _prodGoalService.Insert(pg);
        }
        return Json(new[] { pgvm }.ToDataSourceResult(request, ModelState));
    }

我希望按下按钮将具有 NumberOfEmployees 和 ProductionLineId 的视图模型传递给 CreateNewProductionGoal 方法。

如果需要,我可以尝试澄清更多。

编辑:

var ProductionGoalViewModel = { "NumberOfEmployees": Employees, "ProductionLineId": ProdLineId };
var data = { pgvm: ProductionGoalViewModel }

data: data,

编辑 2:

我现在确定这与我的按钮没有调用 onClick() 方法有关。我在该方法中设置了一个警报,可能应该在不久前这样做,并且该警报从未显示过。有什么建议吗?

<input id="submit" type="button" class="button" value="Submit">

function onClick() {
    var Employees = $("#productiongoal-text").data("kendoNumericTextBox").value();
    var ProdLineId = $("#productionLine-dropdown").data("kendoDropDownList").value();
    var ProductionGoalViewModel = { "NumberOfEmployees": Employees, "ProductionLineId": ProdLineId };
    var data = { pgvm: ProductionGoalViewModel }

    alert("I am an alert box!");

    $.ajax({
        type: 'post',
        url: "ProductionLine/CreateNewProductionGoal",
        dataType: "json",
        data: data,  //Creating a ProductionGoalViewModel to pass into the CreateNewProductionGoal method
        success: function (data) {
            location = location;  //Refreshes the page on button press
        }
    });

}

编辑 3: 我弄清楚了为什么我的按钮永远无法调用 JS 函数。我的按钮是在局部视图中定义的,并且正在调用局部视图的视图不包含正在调用的脚本。非常令人沮丧,但我很高兴我现在能够用我的按钮调用一些东西。但是,我仍然无法调用 CreateNewProductionGoal 方法。我已经更新了原始代码以匹配我目前拥有的代码。

【问题讨论】:

  • 从 ajax 调用中的数据对象中删除 JSON.stringify - 改为发送实际对象。
  • 我试过了,当前的问题是当我按下按钮时,没有调用 CreateNewProductionGoal 方法。但是,这段代码现在应该只是将 ProductionGoalViewModel 传递给方法,对吗?上面编辑中的代码
  • 您的控制器正在接受两个命名输入,但您在提交时没有传递这些命名输入。作为测试,我会尝试将您的数据更改为:data: { pgvm: { NumberOfEmployees: Employees, ProductionLineId: ProdLineId }}
  • 我不确定这是否是问题所在。我一直在尝试以多种不同的方式传递 ProductionGoalViewModel,但没有一个能够调用 CreateNewProductionGoal 方法。查看编辑和其他答案,我都尝试过。也许我的 Button 的创建方式或 JS OnClick() 函数有问题?

标签: javascript c# asp.net-mvc razor kendo-ui


【解决方案1】:

您的代码对我来说似乎都是正确的。使用 JS 时,请确保标签“#___”正确匹配。很多时候,实现这一点可能会让人头疼。

和上面提到的 Hafiz 一样,你需要传递两个参数。

var requestdata ={ };
var pgvmdata = { "NumberOfEmployees": Employees,
                "ProductionLineId": ProdLineId };

var data = {request:requestdata ,pgvm:pgvmdata}
$.ajax({
        url: "/ProductionLine/CreateNewProductionGoal",
        type: 'post',
        dataType: "json",
        data: data,
        success: function (data) {
            location = location;  //Refreshes the page on button press
        }
    });

【讨论】:

  • 哇,我检查了标签,其中一个被一个字符关闭了。感谢您的帮助!
【解决方案2】:

您正面临这个问题只是因为您必须传递两个参数并且您尝试只传递一个。我不知道你必须通过什么来请求请求,所以这取决于你,所以暂时它是空的。

Ajax 请求的样子。

var requestdata ={ };

var pgvmdata = { "NumberOfEmployees": Employees,
                    "ProductionLineId": ProdLineId };

    var data = {request:requestdata ,pgvm:pgvmdata}
    $.ajax({
            url: "/ProductionLine/CreateNewProductionGoal",
            type: 'post',
            dataType: "json",
            data: data,
            success: function (data) {
                location = location;  //Refreshes the page on button press
            }
        });

【讨论】:

    【解决方案3】:

    尝试改变,

           data: JSON.stringify({ 
           //Creating a ProductionGoalViewModel to pass into the CreateNewProductionGoal method
                "ProductionGoalViewModel": {
                    "NumberOfEmployees": Employees,
                    "ProductionLineId": ProdLineId
                }
            }),
    

    到这里

           data: {
               "NumberOfEmployees": Employees,
               "ProductionLineId": ProdLineId
           },
    

    【讨论】:

    • 我试过了,它没有调用 CreateNewProductionGoal 方法。我想知道我的按钮代码是否需要重新编写才能真正调用该方法。这是否仍然有效,以便我的 CreateNewProductionGoal 方法将此输入视为 ProductionGoalViewModel?
    【解决方案4】:

    我给你举个例子。

    var Employees = $("#productiongoal-text").data("kendoNumericTextBox").value();
    var ProdLineId = $("#productionLine-dropdown").data("kendoDropDownList").value();
    
    var ProductionGoalViewModel = {
        NumberOfEmployees: Employees,
        ProductionLineId: ProdLineId
    };
    
    $.ajax({
        url: "ProductionLine/CreateNewProductionGoal",
        type: 'post',
        dataType: "json",
        data: {
            //If your controller is parameterized to accept an object then
            parameter_variable_name: ProductionGoalViewModel
        },
        success: function (data) {
            location = location;  //Refreshes the page on button press
        }
    });
    

    【讨论】:

    • 我尝试更改数据以传递 ViewModel,但仍然无法调用 Create 方法。
    • 您的创建函数是否接受视图模型类型的参数?
    • 我的 CreateNewProductionGoal 接收一个名为 pgvm 的 ProductionGoalViewModel。
    • 那么在data 块的ajax 呼叫中,将parameter_variable_name 更改为pgvm 并拨打电话