仅包含部分C#,MVC

时间:2015-08-21 12:50:44

标签: c# asp.net-mvc linq contains

我有一个供用户选择的员工下拉列表。当用户选择员工时,我会将该值与我的数据库中的值进行比较。如果所选值包含员工的名字和姓氏,那么我应该能够提取他们各自的员工ID。

我的问题是我使用.Contains,并且它只捕获一些员工姓名,即使他们都使用相同的外壳,也不会有错误例如额外的空格,因为员工列表由相同的表填充,我将其与之比较以便找到ID。

 [HttpPost]
    public ActionResult Create(AppViewModel app, App appl, string selectedEmployee)
    {
        //Grabs the value of the selected employee.
        selectedEmployee = Request.Form["selectEmployee"].ToString();

        try
        {
            //TODO: Add insert logic here
            var emp = Database.Session.Query<Employee>().AsEnumerable();

            appl.AppOwnerID = (from e in emp
                               where selectedEmployee.Contains(e.EmpFirstName) && selectedEmployee.Contains(e.EmpLastName)
                               select e.EmplID).First();



            using (ITransaction transaction = Database.Session.BeginTransaction())
            {
                Database.Session.Save(appl);
                transaction.Commit();
            }
            return RedirectToAction("Index");
        }
        catch (Exception ex)
        {

            return View();
        }
    }

出于某种原因,当我选择某些员工时,它能够找到他们的身份证并且工作完美,但对于其他员工而言,它会返回&#34; &#34;因为它的价值因为Contains方法无法找到它们的名字和姓氏。

更新:这是我的列表创建和填充的位置。正如你们所提到的那样使用trim,我在我的列表中添加对象时添加了trim方法,并在将所选值与数据库值进行比较时添加它。

 // GET: App/Create
    public ActionResult Create(string selectEmployee)
    {
        //Holds all employees
        var emp = Database.Session.Query<Employee>().AsEnumerable();

        //Orders employees by last name.
        var empOrdered = emp.OrderBy(e => e.EmpLastName);


        //Formats Employees Names and creates array
        var empName = (from e in empOrdered
                       select e.EmpFirstName + " " + e.EmpLastName).ToArray();

        //List to hold employee names
        var empList = new List<string>();

        //Loops through array to add names into list
        foreach (string empl in empName)
        {
            empList.Add(empl.Trim());
        }

        ViewBag.selectEmployee = new SelectList(empList);

        var model = new AppViewModel();

        return View(new AppViewModel());
    }

第二次更新:以下是我与控制器配合使用的观点。

 @model App_Catalog.Models.AppViewModel
@{
    ViewBag.Title = "Create";
 }

<h2>Create</h2>


@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>AppViewModel</h4>
        <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.AppName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.AppName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.AppName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(m => m.Owner, htmlAttributes: new { @class =      "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("selectEmployee", "Please Select an Employee")
        </div>

    </div>

4 个答案:

答案 0 :(得分:2)

首先 - 将您的Controller签名更改为:

public ActionResult Create(AppViewModel app, App appl, string selectEmployee)

当你这样做时,MVC自动绑定selectEmployee变量,你不再需要这个字符串了:

//Grabs the value of the selected employee.
selectedEmployee = Request.Form["selectEmployee"].ToString();

关于您的查询我相信您正在尝试这样做:

appl.AppOwnerID = emp.FirstOrDefault(e => selectEmployee.Contains(e.EmpFirstName)
                  && selectEmployee.Contains(e.EmpLastName)).EmplID;

正如所有人已经说过的那样 - 可能是你的雇员姓名和姓氏有一些空格。使用Trim()功能确保它不是您的问题。

appl.AppOwnerID = emp.FirstOrDefault(e => selectEmployee.Contains(e.EmpFirstName.Trim())
                  && selectEmployee.Contains(e.EmpLastName.Trim())).EmplID;

答案 1 :(得分:0)

如何根据小写值验证包含? 例如(可以是优化代码)如下:

 where selectedEmployee.ToLowerCase().Contains(e.EmpFirstName.ToLowerCase()) &&
       selectedEmployee.ToLowerCase().Contains(e.EmpLastName.ToLowerCase())

答案 2 :(得分:0)

可能修剪e.EmpFirstNamee.EmpLastName字段,因为它们可以用空格填充。我已经看过很多次了,这会引起很多困惑。

答案 3 :(得分:0)

在检查数据库之前,为什么不删除要检查的每个字符串上的所有空格并修剪两边。

exports.assignRecursiveQuery = function(req, res, next) {
  var query_to_save = []

  var methods = {};

  methods.recursiveChildren = function(path) {
    var item_to_save = {
    	field: path.field.api,
    	match: path.match,
    	value: path.value
    }
    query_to_save.push(item_to_save);

    return new Promise(function(resolve, reject) {
      Path.find({_id: path.parent}).exec(function(err, parentPath) {
        Promise
          .all(parentPath.map(function(parent) {
            /* collect a promise for each child path this returns a promise */
            return methods.recursiveChildren(parent);
          }))
          .then(function(resolvedPaths) {
             /* the top level promise */
            resolve();
          });
      });
   });
  }

  Path.find({_id:req.assignment.path_end}).exec(function(err, paths) {
    Promise.all(paths.map(function(path) {
      return methods.recursiveChildren(path);
    })).then(function(resolvedPaths) {
		var assignment = req.assignment;
   		assignment.assign_query = query_to_save;
   		assignment.save(function(err) {
			if (err) {
				return res.status(400).send({
					message: errorHandler.getErrorMessage(err)
				});
			} else {
				req.assignment = assignment;
				next();
			}
    	});
  	});
  });
};

在尝试使用contains进行匹配之前,对从数据库中提取的记录执行相同的操作。

相关问题