2017-05-04 138 views
0

我正在关注本教程:https://www.codeproject.com/Articles/424461/Implementing-Consuming-ASP-NET-WEB-API-from-JQueryMVC 5 WEB API post

帮助我实现我的web API。但我有些不同。这是我的索引:

@model IEnumerable<dsr_vaja1.Models.Kosarica.Kosarica> 
@{ 
    ViewBag.Title = "kosarica"; 
    Layout = "~/Views/Shared/MasterStran.cshtml"; 
} 


<div id="accordion"> 
    <h3>Igre</h3> 
    <div> 
     <table class="table table-hover "> 
      <tr> 
       <th> 
        @Html.DisplayNameFor(model => model.ime_igre) 
       </th> 
       <th> 
        @Html.DisplayNameFor(model => model.cena_igre) 
       </th> 

      </tr> 
      @foreach (var item in Model) 
      { 
       <tr> 
        <td> 
         @Html.DisplayFor(modelItem => item.ime_igre) 
        </td> 
        <td> 
         @Html.DisplayFor(modelItem => item.cena_igre) 
        </td> 
       </tr> 
      } 
     </table> 
     <button onclick="AddEmployee();return false;">Add Employee</button> 


    </div> 
</div> 

正如你所看到的,在这里我有一个名为Kosarica的项目列表。这是我的网页API:

public void Post(Nakup nakup) 
    { 
     nakup.Id = 1; 
     nc.Nakupi.Add(nakup); 
     nc.SaveChanges(); 
    } 

我的Web API,一切工作完全没问题,现在我只是想知道我怎么会用这个函数:

function AddGame() { 
     jQuery.support.cors = true; 
     var game = { 
      ID: model.id, 
      ime_igre: model.ime_igre, 
     }; 

     $.ajax({ 
      url: 'http://localhost:8080/API_SVC/api/EmployeeAPI', 
      type: 'POST', 
      data:JSON.stringify(employee), 
      contentType: "application/json;charset=utf-8", 
      success: function (data) { 
       WriteResponse(data); 
      }, 
      error: function (x, y, z) { 
       alert(x + '\n' + y + '\n' + z); 
      } 
     }); 
    } 

FOR ALL中的项目用户点击按钮后列出。

**编辑

是不是有一个更简单的方法来做到这一点?我刚刚意识到第一行代码是一个列表 @model IEnumerable

model是一个对象列表。正如你可以在foreach循环中看到的那样,我遍历模型中的项目。那么我能不能简单地将模型传递给j​​query函数?

回答

0

创建一个JavaScript功能,例如:
功能AddGamesForAllItems(){

//通过jQuery选择选择表Here

//在表中的元素环Here

//调用AddGame函数,通过参数表传递所需的元素...你必须在里面声明参数AddGame函数

}

当你需要时调用AddGamesForAllItems函数,例如:Button click event。

希望它可以帮助!

+0

是不是有一个更简单的方法来做到这一点?我刚刚意识到第一行代码是列表 @model IEnumerable model是一个对象列表。正如你可以在foreach循环中看到的那样,我遍历模型中的项目。那么我能不能简单地将模型传递给j​​query函数? – averagejoex

+0

不要忘记,前缀为@前缀的所有代码都是在页面(html)发送给客户端之前,在服务器端执行并呈现的代码。所以,你不能像使用JavaScript一样使用你的模型... –