gpt4 book ai didi

c# - 如何将模型对象或 Viewbag 传递给 Javascript?

转载 作者:行者123 更新时间:2023-11-28 19:50:22 25 4
gpt4 key购买 nike

我正在使用 asp.net mvc4 和 C#。我从学生类(class)的 Getdeutils() 方法中获取详细信息。该方法返回一个数组。 Getdetails 方法也具有与 studentBO 相同的字段。在 Controller 中我有一个如下的方法

   public ActionResult Index()
{
List<studentBO> list = new List<studentBO>();
Student.GetDetails[] dt = Student.Getdeatils();
for (int i = 0; i < dt.Length; i++)
{

studentBO.name= dt[i].name;
studentBO.studentno= dt[i].studentno;
studentBO.address= dt[i].address;
list1.Add(studentBO);
}
ViewBag.Registrationlist = list1;
return View(list1);
}

studentBO 对象有 3 个字段

public class studentBO
{
public long studentno{ get; set; }
public string name{ get; set; }
public string address{ get; set; }
}

How can I get viewbag or model in my Jquery `$(document).ready(function () {}` function. I want to get every students name. So I have to use foreach loop as well.

最佳答案

您可以序列化 ViewBag 中的项目并将其写入 View ,以便 Javascript 代码能够读取它:

$(document).ready(function() {
var registrationList = @(Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewBag.Registrationlist)));
for (var i = 0; i < registrationList.length; i++) {
var studentno = registrationList[i].studentno;
var name= registrationList[i].name;
var address= registrationList[i].address;
// write some more code to make use of the values
}
});

关于c# - 如何将模型对象或 Viewbag 传递给 Javascript?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23556521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com