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

ASP.NET控制器传ID至视图后,如何在JS中获取该ID?

问题描述

我正在使用ASP.NET Controller从另一数据库获取账户数据,实现登录逻辑:获取用户ID并判断其为Mentor(导师)或Student(学生)。希望将该ID传入前端.js文件,用于向服务器发起GET请求,后续还将传入其他信息。

现有控制器代码:

public IActionResult Calendar(LoginViewModel loginViewModel) 
{ 
    Student student = null; 
    Mentor mentor = null; 
    if (loginViewModel.UserType == 0) { 
        student = db.GetStudentObject(loginViewModel.Id); 
    } else if (loginViewModel.UserType == 1) { 
        mentor = db.GetMentorObject(loginViewModel.Id); 
    } 
    if (student != null) { 
        return View(student.Id); 
    }
    if(mentor != null) { 
        return View(mentor.Id); 
    } 
    return View("Index"); 
}

视图初始化时,需在以下AJAX请求中使用控制器传递的ID:

eventSources: [ 
    { 
        url: '/api/Bookings?id=' + id, //we need to access the Id here
        color: 'blue', 
        textColor: 'white' 
    } 
],

请问如何从控制器传递至视图的参数中获取该ID?已知可通过静态类实现,是否有更优方案?


解决方案

嘿,针对你的问题,我给你几个比静态类更靠谱的方案——静态类在多用户并发场景下很容易出现ID混淆的bug,完全不推荐用。下面这些都是ASP.NET里常用的前端传值方式,适配你的场景:

方案1:用ViewBag快速传值(适合简单场景)

这是改动最小的方式,不需要额外定义模型,适合只传单个ID的情况。

先修改控制器代码,把ID存入ViewBag:

public IActionResult Calendar(LoginViewModel loginViewModel) 
{ 
    Student student = null; 
    Mentor mentor = null; 
    int? userId = null;

    if (loginViewModel.UserType == 0) { 
        student = db.GetStudentObject(loginViewModel.Id); 
        userId = student?.Id;
    } else if (loginViewModel.UserType == 1) { 
        mentor = db.GetMentorObject(loginViewModel.Id); 
        userId = mentor?.Id;
    } 

    if (userId.HasValue) { 
        ViewBag.UserId = userId.Value; // 把ID存入ViewBag
        return View(); 
    } 

    return View("Index"); 
}

然后在视图的脚本里直接读取ViewBag的值:

<script>
    // 直接把后端的ID注入到JS变量中
    var userId = @ViewBag.UserId;

    $(document).ready(function() {
        $('#calendar').fullCalendar({
            eventSources: [ 
                { 
                    url: '/api/Bookings?id=' + userId,
                    color: 'blue', 
                    textColor: 'white' 
                } 
            ],
            // 其他日历配置...
        });
    });
</script>

优点:代码改动极小,快速实现;缺点:没有强类型检查,适合短期小需求。

方案2:强类型视图模型(推荐,适合长期维护)

如果后续还要传递更多用户信息(比如区分导师/学生),强类型模型是更规范的选择,能获得编译时检查,避免拼写错误。

首先定义一个专门的视图模型:

public class CalendarViewModel
{
    public int UserId { get; set; }
    public string UserType { get; set; } // 可选,后续区分导师/学生可用
    // 后续需要的其他字段都可以加在这里
}

然后修改控制器,把数据封装到视图模型中传递:

public IActionResult Calendar(LoginViewModel loginViewModel) 
{ 
    Student student = null; 
    Mentor mentor = null; 
    CalendarViewModel calendarVm = null;

    if (loginViewModel.UserType == 0) { 
        student = db.GetStudentObject(loginViewModel.Id); 
        calendarVm = new CalendarViewModel { 
            UserId = student.Id, 
            UserType = "Student" 
        };
    } else if (loginViewModel.UserType == 1) { 
        mentor = db.GetMentorObject(loginViewModel.Id); 
        calendarVm = new CalendarViewModel { 
            UserId = mentor.Id, 
            UserType = "Mentor" 
        };
    } 

    if (calendarVm != null) { 
        return View(calendarVm); 
    } 

    return View("Index"); 
}

在视图顶部指定模型类型,然后直接读取:

@model YourProjectNamespace.CalendarViewModel

<script>
    var userId = @Model.UserId;
    var userType = '@Model.UserType'; // 如果需要区分导师/学生可以用

    $(document).ready(function() {
        $('#calendar').fullCalendar({
            eventSources: [ 
                { 
                    url: '/api/Bookings?id=' + userId,
                    color: 'blue', 
                    textColor: 'white' 
                } 
            ],
            // 其他日历配置...
        });
    });
</script>

优点:强类型安全,扩展性强,长期维护更省心;缺点:需要额外定义模型类,但这点成本完全值得。

方案3:隐藏字段(适合JS代码独立的场景)

如果你的JS代码是放在外部独立的.js文件里(不是内嵌在视图中),可以用隐藏字段存储ID,再让JS读取。

控制器还是用ViewBag或者强类型模型传递ID,然后在视图里加个隐藏字段:

@model YourProjectNamespace.CalendarViewModel

<!-- 用强类型模型的写法 -->
<input type="hidden" id="hiddenUserId" value="@Model.UserId" />

<!-- 用ViewBag的写法:<input type="hidden" id="hiddenUserId" value="@ViewBag.UserId" /> -->

然后在外部JS文件中读取这个隐藏字段的值:

$(document).ready(function() {
    var userId = $('#hiddenUserId').val();

    $('#calendar').fullCalendar({
        eventSources: [ 
            { 
                url: '/api/Bookings?id=' + userId,
                color: 'blue', 
                textColor: 'white' 
            } 
        ],
        // 其他日历配置...
    });
});

优点:保持视图和JS代码的解耦,适合前端代码分离的项目;缺点:多了一步DOM读取,但对性能几乎没有影响。


内容的提问来源于stack exchange,提问作者Boris Grunwald

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 10:01:23