Pass C# Model from View to Javascript

前端 未结 4 1608
耶瑟儿~
耶瑟儿~ 2021-01-24 12:36

I\'m passing this ViewModel to my View:

  public class DashboardViewModel
  {
    public List UserTasks {get; set;}

    public List

        
4条回答
  •  盖世英雄少女心
    2021-01-24 12:59

    @item in View will print out the item as normal string (item.ToString()). I think what you want is to parse the string as a Javascript object, right?

    One approach is to implement a method in your model, like JSON.stringify(). The method can parse the C# model to JSON string:

    {
     "Name" : "Scott",
     "HoursLogged" : "2"
    }
    

    Then you can parse the string to JSON object in View by using JSON.parse(). In this case, you can use the JSON object. Some thoughts:

    C#:

    public class Item
    {
     public string Name { get; set; }
     public int HoursLogged { get; set; }
     public string ToJsonString()
     {
      return "{" + "\"Name\":" + Name + ",HoursLogged:" + HoursLogged + "}";
     }
    }
    

    JS:

    var jsonStr = '@item.ToJsonString()';
    var jsonObj = JSON.parse(jsonStr);
    console.log(jsonObj.Name);
    console.log(jsonObj.HoursLogged);
    

    You can also use Newton to stringify C# model.

提交回复
热议问题