Pass C# Model from View to Javascript

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

I\'m passing this ViewModel to my View:

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

    public List

        
相关标签:
4条回答
  • You should store the data you use to loop to a javascript variable and query that when your button is clicked. Keep a unique identifier on your button' data attribute which you can use to query later. Since it is an array, you can simply use a counter variable which matches with the (js) array index.

    @{ var counter = 0;}
    @foreach (var item in Model.WorkItems)
     {
        @item.Name
        <button class="updateBtns" data-index="@counter">UPDATE</button>
        counter++;
     }
    

    and in the same razor view, have this javascript where you will serialize the Model.WorkItems collection to a javascript array and store it in a variable.

    <script>
      $(function() { 
    
         var dataArr = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.WorkItems));
          $(".updateBtns").click(function (e) {
              e.preventDefault();
    
              var selectedItem = dataArr[$(this).data("index")];
              console.log(selectedItem);
          });    
      });    
    </script>
    
    0 讨论(0)
  • 2021-01-24 12:48

    I normally use this to translate from MVC to javascript!

    @Html.Raw(Json.Encode(item))
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-24 13:00

    You should probably take a few steps back to understand what is going on here. A web request is really just a bunch of strings, MVC .net does some stuff to try and ease the transition from using objects to just straight string but as you can see it can't do everything. So the take-away is that you to deal with things as if they are all strings when rendered on the page.

    That being said there are a number of ways to solve this problem. You can as mentioned before convert all your WorkItem objects to javascript objects and pull them out of the javascript array. Or what I personally like to do is simply have the button contain the id of the object and do an ajax call to get the most recent data from the server.

    Back end:

    [HttpPost]
    public string GetWorkItemById(int id)
    {
    
    //get or create WorkItem here
    WorkItem workItem = new WorkItem(id);
    workItem.Name = "Foobar";
    workItem.HoursLogged = "127001";
    
    return Newtonsoft.Json.JsonConvert.SerializeObject(workItem);
    }
    

    Front end:

        $(buttonEl).click(function () {    
        var id = this.value; //assuming you store the id in the button's value
        $.ajax({
              type: "POST",
              url: "@(Url.Action("GetWorkItemById"))",
              data: ({
                        Id:id
                     }),
              success: success,
              dataType: dataType, 
              success: function(result){
                    var name = result.Name; // Foobar
                    var hoursLogged = result.HoursLogged; // 127001
                    //populate text fields using jquery
              }
            })
        });
    
    0 讨论(0)
提交回复
热议问题