在我的控制器中,我有一个名为“ SearchForContact ”的动作方法,它采用2个字符串参数 firstName 和 LastName 。有三种情况:
如果两个参数均为null,则会重新显示视图并显示错误消息,提示用户至少输入其中一个参数
如果两个参数都不为null,我可以检索联系人并在视图上显示结果
这是处理搜索的声明:
var contacts = contactRepository.SearchForContacts(firstName, lastName).ToList();
以下是位于models文件夹中的我的存储库类(ContactRepository.cs)中的帮助器方法。
public IQueryable<Contact> SearchForContacts(string firstName, string lastName)
{
if (firstName == null)
return OneCriteria(lastName);
if (nom == null)
return OneCriteria(firstName);
else
return TwoCriteria(firstName, lastName);
}
private IQueryable<Contact> OneCriteria(string criteria)
{
var contacts = from contact in db.Contacts
where ((contact. firstName == criteria) ||
(contact. lastName == criteria))
orderby contact. firstName
select contact;
return contacts;
}
private IQueryable<Contact> TwoCriteria(string firstName, string lastName)
{
var contacts = from contact in db.Contacts
where ((contact. firstName == firstName) &&
(contact. lastName == lastName))
orderby contact. firstName
select contact;
return contacts;
}
感谢您的帮助
答案 0 :(得分:2)
你不应该改变
if (nom == null)
到
if (lastName== null)
我测试时似乎工作正常。
答案 1 :(得分:0)
试试这个
if ((firstName == null) && (lastName != null) )
return OneCriteria(lastName);
if((firstName!= null)&amp;&amp;(lastName == null)) return OneCriteria(firstName);
否则 返回TwoCriteria(firstName,lastName);
希望这会有所帮助。
答案 2 :(得分:0)
您可以尝试以下方法: if(firstName == null&amp;&amp; lastname == null) {做你的错误}
否则 {
var contacts =来自db.Contacts中的联系人选择联系人;
if(firstName!= null)contacts = from FN in contacts(FN.firstName == firstName)选择FN;
if(lastName!= null)contacts = from LN中的联系人,其中(FN.lastName == lastName)选择LN;
}