You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在.cshtml中将HTML元素值传递给C#方法?调用报错求助

问题分析

  • 第一种方式错误:@Model.setlaneOnFloor(floor,lane)是服务器端代码,页面渲染阶段就会执行,此时客户端JS的floor、lane变量还未生成,服务器无法识别这些客户端变量;同时直接传递DOM元素给C#方法,也不符合参数类型要求。
  • 第二种方式错误:document.getElementById("floor")获取的是DOM元素对象,不是元素的数值;URL写法沿用了ASPX的ResolveUrl,Razor视图中应使用MVC的URL生成方式;另外MVC项目中,WebMethod通常放在Controller而非Model中。

正确实现方案

方案1:使用MVC Controller Action(推荐)

1. 编写Controller中的Action方法
public class YourController : Controller
{
    [HttpPost]
    public JsonResult SetLaneOnFloor(int floor, int num)
    {
        // 调用业务逻辑方法
        string result = cmd.setlaneinsection(floor, num);
        return Json(result, JsonRequestBehavior.AllowGet);
    }
}
2. Razor视图(.cshtml)中的JS代码
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function setlane() {
    // 获取输入框的数值(假设floor、lane是input元素)
    let floorValue = parseInt(document.getElementById("floor").value);
    let laneValue = parseInt(document.getElementById("lane").value);

    // 验证输入有效性
    if (isNaN(floorValue) || isNaN(laneValue)) {
        alert("请输入有效的数字");
        return;
    }

    $.ajax({
        type: "POST",
        // 生成正确的Action请求地址
        url: '@Url.Action("SetLaneOnFloor", "YourController")',
        // 参数名需与Action方法的参数名完全一致
        data: { floor: floorValue, num: laneValue },
        success: function (msg) {
            $("#txtStartDate").val(msg);
        },
        error: function (xhr, status, error) {
            console.log("请求出错:" + error);
        }
    });
}
</script>

方案2:使用WebMethod(适配WebForms或混合项目)

1. 编写Controller中的静态WebMethod
using System.Web.Script.Services;

public class YourController : Controller
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static string SetLaneOnFloor(int floor, int num)
    {
        string result = cmd.setlaneinsection(floor, num);
        return result;
    }
}
2. Razor视图中的JS代码
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
function setlane() {
    let floorValue = parseInt(document.getElementById("floor").value);
    let laneValue = parseInt(document.getElementById("lane").value);

    if (isNaN(floorValue) || isNaN(laneValue)) {
        alert("请输入有效的数字");
        return;
    }

    $.ajax({
        type: "POST",
        url: '@Url.Action("SetLaneOnFloor", "YourController")',
        data: JSON.stringify({ floor: floorValue, num: laneValue }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $("#txtStartDate").val(msg.d);
        },
        error: function (xhr, status, error) {
            console.log("请求出错:" + error);
        }
    });
}
</script>

关键注意点

  • 必须获取HTML元素的值(.value),而非元素本身;若为非输入类元素(如span),可使用.innerText获取内容后转成数字。
  • 确保JS传递的参数名与C#方法的参数名完全一致,否则无法完成参数绑定。
  • MVC项目优先使用Action方法,WebMethod更适合WebForms场景。

内容的提问来源于stack exchange,提问作者Atithep Jarungsathitphong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 05:54:55