How to load data employee on view GetAllEmpDetails.cshtml based on drop down selected index changed?

huangapple go评论60阅读模式
英文:

How to load data employee on view GetAllEmpDetails.cshtml based on drop down selected index changed?

问题

我在使用C#和ADO.NET开发MVC Web应用程序,遇到一个问题,即无法根据下拉列表的选择索引更改来显示员工数据。

如果用户从下拉列表中选择“Pending Request”,则应选择员工状态为1的员工。

如果用户从下拉列表中选择“Done Request”,则应选择员工状态为2的员工。

我的代码如下:

表结构

CREATE TABLE [dbo].[Employee](
    [EmployeeId] [int] NOT NULL,
    [EmployeeName] [nvarchar](100) NULL,
    [EmployeeStatus] [int] NULL,
 CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
(
    [EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [EmployeeStatus]) VALUES (1211, N'ahmed', 1)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [EmployeeStatus]) VALUES (1222, N'eslam', 1)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [EmployeeStatus]) VALUES (1223, N'adel', 2)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [EmployeeStatus]) VALUES (1224, N'mohamed', 2)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [EmployeeStatus]) VALUES (1225, N'mosh', 2)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [EmployeeStatus]) VALUES (1227, N'ali', 1)
存储过程有逻辑

create Procedure [dbo].[LoadDropDownEmployee] 
@EmployeeStatus int
as  
begin  
   select * from Employee  where EmployeeStatus=@EmployeeStatus
End 

create Procedure [dbo].[GetEmployees]  
as  
begin  
   select *from Employee  
End 
员工模型

public class EmpModel
{
    public int EmployeeId { get; set; }
    public string EmployeeName { get; set; }
    public int EmployeeStatus { get; set; }
}
员工仓库有用于控制器的函数

public List<EmpModel> GetAllEmployees()
{
    connection();
    List<EmpModel> EmpList = new List<EmpModel>();

    SqlCommand com = new SqlCommand("GetEmployees", con);
    com.CommandType = CommandType.StoredProcedure;
    SqlDataAdapter da = new SqlDataAdapter(com);
    DataTable dt = new DataTable();

    con.Open();
    da.Fill(dt);
    con.Close();   
    foreach (DataRow dr in dt.Rows)
    {
        EmpList.Add(
            new EmpModel
            {
                EmployeeId = Convert.ToInt32(dr["EmployeeId"]),
                EmployeeName = Convert.ToString(dr["EmployeeName"]),
                EmployeeStatus = Convert.ToInt32(dr["EmployeeStatus"])
            }
        );
    }

    return EmpList;
}

public List<EmpModel> LoadDropDownLists(int EmployeeStatus)
{
    connection();
    List<EmpModel> EmpList = new List<EmpModel>();

    SqlCommand com = new SqlCommand("LoadDropDownEmployee", con);
    com.CommandType = CommandType.StoredProcedure;
    com.Parameters.Add("@EmployeeStatus", SqlDbType.VarChar, 50);
    com.Parameters["@EmployeeStatus"].Value = EmployeeStatus;
    SqlDataAdapter da = new SqlDataAdapter(com);
    DataTable dt = new DataTable();

    con.Open();
    da.Fill(dt);
    con.Close();  
    foreach (DataRow dr in dt.Rows)
    {
        EmpList.Add(
            new EmpModel
            {
                EmployeeId = Convert.ToInt32(dr["EmployeeId"]),
                EmployeeName = Convert.ToString(dr["EmployeeName"])
            }
        );
    }

    return EmpList;
}

控制器Employee

public class EmployeeController : Controller
{
    public ActionResult LoadDropDownList(int EmployeeStatus)
    {
        EmpRepository EmpRepo = new EmpRepository();
        return View();
    }

    public ActionResult GetAllEmpDetails()
    {
        EmpRepository EmpRepo = new EmpRepository();
        ModelState.Clear();
        return View(EmpRepo.GetAllEmployees());
    }
}

视图GetAllEmpDetails.cshtml

@model IEnumerable<Ado.netMvc.Models.EmpModel>

@{
    ViewBag.Title = "GetAllEmpDetails";
}

<h2>GetAllEmpDetails</h2>

<th>
    <select class="form-control" id="statusselect" name="statusselectName">
        <option>Select Status</option>
        <option>Pending Request</option>
        <option>All requests </option>
    </select>
</th>

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.EmployeeId)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.EmployeeName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.EmployeeStatus)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.EmployeeId)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.EmployeeName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.EmployeeStatus)
            </td>
        </tr>
    }
</table>

**所以,在下拉列表`statusselect`的选择索引更改时,如何在视图`GetAllEmpDetails`上获取数据?**
英文:

I work on MVC web application using c# by ado.net I face issue I can't display employee data based on drop down selected index changed .

so

if user select Pending Request from drop down list it will select employee that have select employee status 1 .

if user select Done Request from drop down list it will select employee that have select employee status 2 .

my code as below :

Table structure

CREATE TABLE [dbo].[Employee](
[EmployeeId] [int] NOT NULL,
[EmployeeName] [nvarchar](100) NULL,
[EmployeeStatus] [int] NULL,
CONSTRAINT [PK_Employee] PRIMARY KEY CLUSTERED 
(
[EmployeeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [EmployeeStatus]) VALUES (1211, N&#39;ahmed&#39;, 1)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [EmployeeStatus]) VALUES (1222, N&#39;eslam&#39;, 1)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [EmployeeStatus]) VALUES (1223, N&#39;adel&#39;, 2)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [EmployeeStatus]) VALUES (1224, N&#39;mohamed&#39;, 2)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [EmployeeStatus]) VALUES (1225, N&#39;mosh&#39;, 2)
INSERT [dbo].[Employee] ([EmployeeId], [EmployeeName], [EmployeeStatus]) VALUES (1227, N&#39;ali&#39;, 1)

stored procedures have logic

create Procedure [dbo].[LoadDropDownEmployee] 
@EmployeeStatus int
as  
begin  
select * from Employee  where EmployeeStatus=@EmployeeStatus
End 
create Procedure [dbo].[GetEmployees]  
as  
begin  
select *from Employee  
End 

Employee Model

public class EmpModel
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public int EmployeeStatus { get; set; }
}

Employee Repository have functions for controller

public List&lt;EmpModel&gt; GetAllEmployees()
{
connection();
List&lt;EmpModel&gt; EmpList = new List&lt;EmpModel&gt;();
SqlCommand com = new SqlCommand(&quot;GetEmployees&quot;, con);
com.CommandType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
con.Open();
da.Fill(dt);
con.Close();   
foreach (DataRow dr in dt.Rows)
{
EmpList.Add(
new EmpModel
{
EmployeeId = Convert.ToInt32(dr[&quot;EmployeeId&quot;]),
EmployeeName = Convert.ToString(dr[&quot;EmployeeName&quot;]),
EmployeeStatus = Convert.ToInt32(dr[&quot;EmployeeStatus&quot;])
}
);
}
return EmpList;
}
public List&lt;EmpModel&gt; LoadDropDownLists(int EmployeeStatus)
{
connection();
List&lt;EmpModel&gt; EmpList = new List&lt;EmpModel&gt;();
SqlCommand com = new SqlCommand(&quot;LoadDropDownEmployee&quot;, con);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.Add(&quot;@EmployeeStatus&quot;, SqlDbType.VarChar, 50);
com.Parameters[&quot;@EmployeeStatus&quot;].Value = EmployeeStatus;
SqlDataAdapter da = new SqlDataAdapter(com);
DataTable dt = new DataTable();
con.Open();
da.Fill(dt);
con.Close();  
foreach (DataRow dr in dt.Rows)
{
EmpList.Add(
new EmpModel
{
EmployeeId = Convert.ToInt32(dr[&quot;EmployeeId&quot;]),
EmployeeName = Convert.ToString(dr[&quot;EmployeeName&quot;])
}
);
}
return EmpList;
}

controller Employee

public class EmployeeController : Controller
{
public ActionResult LoadDropDownList(int EmployeeStatus)
{
EmpRepository EmpRepo = new EmpRepository();
return View();
}
public ActionResult GetAllEmpDetails()
{
EmpRepository EmpRepo = new EmpRepository();
ModelState.Clear();
return View(EmpRepo.GetAllEmployees());
}
}

view GetAllEmpDetails.cshtml

@model IEnumerable&lt;Ado.netMvc.Models.EmpModel&gt;
@{
ViewBag.Title = &quot;GetAllEmpDetails&quot;;
}
&lt;h2&gt;GetAllEmpDetails&lt;/h2&gt;
&lt;th&gt;
&lt;select class=&quot;form-control&quot; id=&quot;statusselect&quot; name=&quot;statusselectName&quot;&gt;
&lt;option&gt;Select Status&lt;/option&gt;
&lt;option&gt;Pending Request&lt;/option&gt;
&lt;option&gt;All requests &lt;/option&gt;
&lt;/select&gt;
&lt;/th&gt;
&lt;table class=&quot;table&quot;&gt;
&lt;tr&gt;
&lt;th&gt;
@Html.DisplayNameFor(model =&gt; model.EmployeeId)
&lt;/th&gt;
&lt;th&gt;
@Html.DisplayNameFor(model =&gt; model.EmployeeName)
&lt;/th&gt;
&lt;th&gt;
@Html.DisplayNameFor(model =&gt; model.EmployeeStatus)
&lt;/th&gt;
&lt;th&gt;&lt;/th&gt;
&lt;/tr&gt;
@foreach (var item in Model)
{
&lt;tr&gt;
&lt;td&gt;
@Html.DisplayFor(modelItem =&gt; item.EmployeeId)
&lt;/td&gt;
&lt;td&gt;
@Html.DisplayFor(modelItem =&gt; item.EmployeeName)
&lt;/td&gt;
&lt;td&gt;
@Html.DisplayFor(modelItem =&gt; item.EmployeeStatus)
&lt;/td&gt;
&lt;/tr&gt;
}
&lt;/table&gt; 

so How to get data on view GetAllEmpDetails when drop down statusselect selected index changed ?

答案1

得分: 1

请将员工列表移到一个局部视图中。这样,GetAllEmpDetails.cshtml视图将如下所示。在主视图上的ajax调用从Employee Controller的GetAllEmpDetailsByStatus ActionResult方法中渲染局部视图。此外,我在选择输入的选项中添加了值,因为我们需要将此值传递给GetAllEmpDetailsByStatus方法并筛选员工数据。

@model IEnumerable<Ado.netMvc.Models.EmpModel>

@{
    ViewBag.Title = "GetAllEmpDetails";
}

<script type="text/javascript">
    $(document).ready(function () {
        $("#statusselect").change(function () {

              var postData = {
                  empStatus: $(this).val()
                };

                $.ajax({
                    cache: false,
                    type: 'POST',
                    url: '../Employee/GetAllEmpDetailsByStatus',
                    data: postData,
                    dataType: 'json',
                    success: function (data) {
                        $("#employeeContainer").html(data.html);
                    },
                    failure: function () {

                    }
                });
        });
    });
</script>
<h2>GetAllEmpDetails</h2>
<th>
    <select class="form-control" id="statusselect" name="statusselectName">
        <option value="1">选择状态</option>
        <option value="2">待处理请求</option>
        <option value="0">所有请求</option>
    </select>
</th>

<div id="employeeContainer">
  @Html.Partial("_AllEmployee", Model)
</div>

以下是局部视图:

@model IEnumerable<Ado.netMvc.Models.EmpModel>

<table class="table">
    <tr>

        <th>
            员工ID
        </th>
        <th>
            员工姓名
        </th>
        <th>
             员工状态
        </th>
    </tr>

    @foreach (var item in Model)
    {

        <tr>

            <td>
                @Html.DisplayFor(modelItem => item.EmployeeId)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.EmployeeName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.EmployeeStatus)
            </td>

        </tr>
    }
</table>

EmployeeController的GetAllEmpDetailsByStatus() ActionResult方法如下:

public class EmployeeController : Controller
{
    [HttpPost]
    public ActionResult GetAllEmpDetailsByStatus(int empStatus)
    {
        EmpRepository EmpRepo = new EmpRepository();
        ModelState.Clear();
        var theData = EmpRepo.LoadDropDownLists(empStatus);

        return Json(new
        {
            html = RenderPartialViewToString("_AllEmployee", theData)
        });
    }

    public virtual string RenderPartialViewToString(string viewName, object model)
    {
        if (string.IsNullOrEmpty(viewName))
            viewName = this.ControllerContext.RouteData.GetRequiredString("action");

        this.ViewData.Model = model;

        using (var sw = new StringWriter())
        {
            ViewEngineResult viewResult = System.Web.Mvc.ViewEngines.Engines.FindPartialView(this.ControllerContext, viewName);
            var viewContext = new ViewContext(this.ControllerContext, viewResult.View, this.ViewData, this.TempData, sw);
            viewResult.View.Render(viewContext, sw);

            return sw.GetStringBuilder().ToString();
        }
    }
}
英文:

Please move the employee list to a partial view. So the GetAllEmpDetails.cshtml view will be like the below. The ajax call on the main view to render the partial view from the ActionResult method GetAllEmpDetailsByStatus of Employee Controller. Also I add value to the option of the select input. Because we need to pass this value to the GetAllEmpDetailsByStatus method and filter the employee data.

@model IEnumerable&lt;Ado.netMvc.Models.EmpModel&gt;
@{
ViewBag.Title = &quot;GetAllEmpDetails&quot;;
}
&lt;script type=&quot;text/javascript&quot;&gt;
$(document).ready(function () {
$(&quot;#statusselect&quot;).change(function () {
var postData = {
empStatus: $(this).val()
};
//addAntiForgeryToken(postData);
$.ajax({
cache: false,
type: &#39;POST&#39;,
url: &#39;../Employee/GetAllEmpDetailsByStatus&#39;,
data: postData,
dataType: &#39;json&#39;,
success: function (data) {
$(&quot;#employeeContainer&quot;).html(data.html);
},
failure: function () {
}
});
});
});
&lt;/script&gt;
&lt;h2&gt;GetAllEmpDetails&lt;/h2&gt;
&lt;th&gt;
&lt;select class=&quot;form-control&quot; id=&quot;statusselect&quot; name=&quot;statusselectName&quot;&gt;
&lt;option value=&quot;1&quot;&gt;Select Status&lt;/option&gt;
&lt;option value=&quot;2&quot;&gt;Pending Request&lt;/option&gt;
&lt;option value=&quot;0&quot;&gt;All requests &lt;/option&gt;
&lt;/select&gt;
&lt;/th&gt;
&lt;div id=&quot;employeeContainer&quot;&gt;
@Html.Partial(&quot;_AllEmployee&quot;, Model)
&lt;/div&gt;

The Partial View below

@model IEnumerable&lt;Ado.netMvc.Models.EmpModel&gt;
&lt;table class=&quot;table&quot;&gt;
&lt;tr&gt;
&lt;th&gt;
Employee Id
&lt;/th&gt;
&lt;th&gt;
Employee Name
&lt;/th&gt;
&lt;th&gt;
Employee Status
&lt;/th&gt;
&lt;/tr&gt;
@foreach (var item in Model)
{
&lt;tr&gt;
&lt;td&gt;
@Html.DisplayFor(modelItem =&gt; item.EmployeeId)
&lt;/td&gt;
&lt;td&gt;
@Html.DisplayFor(modelItem =&gt; item.EmployeeName)
&lt;/td&gt;
&lt;td&gt;
@Html.DisplayFor(modelItem =&gt; item.EmployeeStatus)
&lt;/td&gt;
&lt;/tr&gt;
}
&lt;/table&gt;
The GetAllEmpDetailsByStatus() ActionResult method of EmployeeController is like the below.
public class EmployeeController : Controller
{
[HttpPost]
public ActionResult GetAllEmpDetailsByStatus(int empStatus)
{
EmpRepository EmpRepo = new EmpRepository();
ModelState.Clear();
var theData= EmpRepo.LoadDropDownLists(empStatus);
return Json(new
{
html = RenderPartialViewToString(&quot;_AllEmployee&quot;, theData)
});
}
// Better to move the base class, like BaseController.
public virtual string RenderPartialViewToString(string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = this.ControllerContext.RouteData.GetRequiredString(&quot;action&quot;);
this.ViewData.Model = model;
using (var sw = new StringWriter())
{
ViewEngineResult viewResult = System.Web.Mvc.ViewEngines.Engines.FindPartialView(this.ControllerContext, viewName);
var viewContext = new ViewContext(this.ControllerContext, viewResult.View, this.ViewData, this.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}
}

huangapple
  • 本文由 发表于 2023年2月6日 09:08:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75356578.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定