如何获得asp.net mvc中按钮单击时输入的ID?

问题描述 投票:-1回答:1

我靠asp.net。当用户单击按钮时,我想将产品的ID作为参数传递。以前,我曾使用js和ajax完成此操作,但现在我想使用代码优先方法在asp.net中进行此操作。

问题是,如何从数据库中单击按钮获得ID作为输入。

我正在使用的参考代码是:

public ActionResult Details(string id)  
 {  
     int empId = Convert.ToInt32(id);  
     var emp = objDataContext.employees.Find(empId);  
     return View(emp);  
 }  

我应该使用ID作为参数或Model对象,这是一种更好的方法

 public ActionResult create(int id)

OR

 public ActionResult create(Model model)

请在这方面指导我

asp.net asp.net-mvc
1个回答
0
投票

您需要传递给方法的参数取决于您的要求。由于您的Details方法仅需要ID即可获取数据,因此传递ID就足够了。

如果您要在方法中添加数据,则可以传递整个模型。

假设您有这样的模型。

public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

然后您将这些模型数据传递给控制器​​的视图。

public ActionResult Index()
        {
            List<Employee> emps = new List<Employee>();
            Employee employee1 = new Employee(){Id = 1,Name = "Test1"};
            Employee employee2 = new Employee(){Id = 2,Name = "Test2"};

            emps.Add(employee1);
            emps.Add(employee2);


            return View(emps);
        }

您可以从视图传递特定数据或整个模型。用户@Url.Action呼叫控制器。

这里是视图:

@model IEnumerable<MyWebApplication.Models.Employee>

    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.Name)
            </td>
            <td>
               <a class="btn btn-default" href="@Url.Action("Details", "Home", new { id=item.Id })">Details</a> |
               <a class="btn btn-default" href="@Url.Action("Create", "Home", new { model=item })">Create</a>
            </td>
        </tr>

这里是控制器:

   public ActionResult Details(string id)  
     {  
         int empId = Convert.ToInt32(id);  
         var emp = objDataContext.employees.Find(empId);  
         return View(emp);  
     }  

 public ActionResult create(Model model){
      //.......code
 }

使用@Url.Action将数据调用到控制器。

希望这会有所帮助。

© www.soinside.com 2019 - 2024. All rights reserved.