显示从控制器到视图的特定用户数据

时间:2013-02-25 12:57:43

标签: asp.net-mvc-3 sql-server-2008

我在asp.net mvc做一个项目。我想在视图中显示特定人员的详细信息。我必须加入2个表来显示数据。为此我做了:

控制器:

[HttpGet]
public ViewResult DisplayData()  
{  
    ViewBag.Designation1up = new SelectList(db.Designations, "Designation1up", "DesignationInternal", "DesignationExternal");  
    return View();  
}  

[HttpPost]  
public ActionResult DisplayData(Employee emp)  
{  
    try  
    {  
        object s = Session["EmployeeID"];  
        var sessval = s.ToString();  
        var data1 = (from e in db.Employees.Where(c => c.EmployeeID == sessval) join d in db.Designations on e.Designation1up equals d.Designation1up select e).SingleOrDefault();  
        return View(data1);  
    }  
    catch (Exception e)  
    {  
    }  
    ViewBag.Designation1up = new SelectList(db.Designations, "Designation1up", "DesignationInternal",emp.Designation1up);  
    return View(emp);     
}

观点:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<ResourceTracking.ViewModel.AdminDetailsModel>" %> 
<!DOCTYPE html> 
<html> 
  <head runat="server"> 
    <title>DisplayData</title> 
  </head> 
  <body> 
    <fieldset> 
      <legend>AdminDetailsModel</legend> 
      <div class="display-label">EmployeeID</div> 
      <div class="display-field"> <%: Html.DisplayFor(model => model.EmployeeID) %> </div> 
      <!--...(same DIV 4 other fields)-->
   </fieldset>  
  </body> 
</html> 

我的问题是,当我调试代码时,编译器不会进入HttpPost方法。它只是调试HttpGet方法并提供输出,但除非运行HttpPost,否则输出将不正确。我该怎么做?

1 个答案:

答案 0 :(得分:0)

我认为你对ASP.NET MVC的工作原理有点困惑。通常,要在视图上显示数据,您将调用HttpGet操作(DisplayData),创建模型,使用相关数据(员工)填充模型并显示它。

像这样(未经测试)

[HttpGet]
public ViewResult DisplayData()  
{  
    ViewBag.Designation1up = new SelectList(db.Designations, "Designation1up", "DesignationInternal", "DesignationExternal");  

    SomeModel model = new SomeModel();

    object s = Session["EmployeeID"];  
    if (s != null)
    {
        var employeeId = s.ToString();  

        model.EmployeeData = GetEmployeeData(employeeId);
    }

    return View(model);  
}  

private Employee GetEmployeeData(string employeeId)  
{  
    return (from e in db.Employees.Where(c => c.EmployeeID == employeeId) 
            join d in db.Designations 
                on e.Designation1up equals d.Designation1up 
            select e).SingleOrDefault();  
}