在我的一个asp.net mvc项目中,我想为我的域实体提供自动完成功能和一般数据源URL以及键入自动完成功能。我正在寻找asp.net mvc helper
答案 0 :(得分:-1)
当我在ASP.NET MVC中启动我的新项目时,我需要为许多域实体(部门,员工,产品,类别等)提供类似自动完成的输入控件,并用于通用目的。我只是想使用自动完成而不是下拉列表
当需要向最终用户提供自动建议类型的数据输入时,这非常有用
在选择回叫和源URL上,需要具有各种重载的两个助手,具有属性,自动完成类型。一个帮助程序用于强类型视图,另一个帮助程序用于没有模型绑定的视图
工作原理
Helper创建两个html输入元素,一种隐藏文本和其他类型的文本。隐藏的ID和名称是开发人员给出的自动完成名称或模型属性名称。文本框的ID和名称将是隐藏_AutoComplete的名称(例如:隐藏名称为ProductID,文本框名称为ProductID_Auto Complete)。文本框中显示的选定文本和选定值将转到隐藏控件。在提交当前表单时,隐藏和文本的值都将被提交给服务器。
如果我们为控件指定源URL,则它从指定的url获取数据。在其他情况下,如果我们指定自动完成的类型,则数据从预定义的URL加载。
可以指定JavaScript回调函数在从自动完成
中选择项目后执行可以使用参数IsRequired = true
添加客户端所需的验证测试要求 •Visual Studio 2013 •ASP.NET MVC 5 •jQuery的1.10.2 •jquery-ui-1.8.23.custom.min自动完成插件
使用代码
代码块包含以下资源
•部门,员工(此附加源的c#类域实体)
•AutocompleteHelper(用于定义帮助程序的c #stitick类)
•TestAutoCompleteController(c#MVC控制器类将数据返回到自动完成请求)
•CustomAutoComplete脚本(用于处理来自客户端的自动完成请求和响应的Jquery脚本)
•查看(Index.cshtml以设计示例视图)
首先定义一个Enum,以根据实体名称指定要加载的数据类型
自动完成助手
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace AutoCompleteHelper_MVC.Extensions
{
public enum AutoCompleteType
{
None,
Department,
Employee,
}
public static class AutoCompleteHelper
{
public static MvcHtmlString Autocomplete(this HtmlHelper helper, string name, string value, string text, string actionUrl, bool? isRequired = false, IDictionary<string, object> viewhtmlAttributes = null, string onselectfunction = "")
{
return GetAutocompleteString(helper, name, value, text, AutoCompleteType.None, actionUrl, isRequired, viewhtmlAttributes, onselectfunction: onselectfunction);
}
public static MvcHtmlString Autocomplete(this HtmlHelper helper, string name, string value, string text, AutoCompleteType autoCompleteType, bool? isRequired = false, IDictionary<string, object> viewhtmlAttributes = null, string onselectfunction = "")
{
return GetAutocompleteString(helper, name, value, text, autoCompleteType, "", isRequired: isRequired, viewhtmlAttributes: viewhtmlAttributes, onselectfunction: onselectfunction);
}
private static MvcHtmlString GetAutocompleteString(HtmlHelper helper, string name, string value, string text, AutoCompleteType autoCompleteType, string actionUrl = "", bool? isRequired = false, IDictionary<string, object> viewhtmlAttributes = null, string onselectfunction = "")
{
return GetHelperString(helper, name, value, text, autoCompleteType, actionUrl, isRequired, viewhtmlAttributes, onselectfunction);
}
public static MvcHtmlString AutocompleteFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string DisplayProperty, string actionUrl, bool? isRequired = false, IDictionary<string, object> viewhtmlAttributes = null, string onselectfunction = "")
{
return GetAutocompleteForString(helper, expression, DisplayProperty, AutoCompleteType.None, actionUrl, isRequired, viewhtmlAttributes, onselectfunction: onselectfunction);
}
public static MvcHtmlString AutocompleteFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string DisplayProperty, AutoCompleteType autoCompleteType, bool? isRequired = false, IDictionary<string, object> viewhtmlAttributes = null, string onselectfunction = "")
{
return GetAutocompleteForString(helper, expression, DisplayProperty, autoCompleteType, "", isRequired: isRequired, viewhtmlAttributes: viewhtmlAttributes, onselectfunction: onselectfunction);
}
private static MvcHtmlString GetAutocompleteForString<TModel, TValue>(HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string DisplayText, AutoCompleteType autoCompleteType, string actionUrl = "", bool? isRequired = false, IDictionary<string, object> viewhtmlAttributes = null, string onselectfunction = "")
{
string name = ((MemberExpression)expression.Body).ToString();
name = name.Substring(name.IndexOf('.') + 1);
Func<TModel, TValue> method = expression.Compile();
object value = null;
if (helper.ViewData.Model != null)
value = method((TModel)helper.ViewData.Model);
return GetHelperString(helper, name, (value != null ? value.ToString() : ""), DisplayText, autoCompleteType, actionUrl, isRequired, viewhtmlAttributes, onselectfunction);
}
private static MvcHtmlString GetHelperString(HtmlHelper helper, string name, string value, string text, AutoCompleteType autoCompleteType, string actionUrl = "", bool? isRequired = false, IDictionary<string, object> viewhtmlAttributes = null, string onselectfunction = "")
{
if (autoCompleteType != AutoCompleteType.None)
{
UrlHelper url = new UrlHelper(helper.ViewContext.RequestContext);
string acpath = url.Content("~/TestAutoComplete/");
if (autoCompleteType == AutoCompleteType.Department)
actionUrl = acpath + "GetDepartments";
else if (autoCompleteType == AutoCompleteType.Employee)
actionUrl = acpath + "GetEmployees";
}
if (viewhtmlAttributes == null)
viewhtmlAttributes = new Dictionary<string, object>();
viewhtmlAttributes.Add("data-autocomplete", true);
viewhtmlAttributes.Add("data-autocompletetype", autoCompleteType.ToString().ToLower());
viewhtmlAttributes.Add("data-sourceurl", actionUrl);
if (!string.IsNullOrEmpty(onselectfunction))
{
viewhtmlAttributes.Add("data-selectfunction", onselectfunction);
}
if (isRequired.HasValue && isRequired.Value)
{
viewhtmlAttributes.Add("data-val", "true");
viewhtmlAttributes.Add("data-val-required", name + " is required");
}
viewhtmlAttributes.Add("data-valuetarget", name);
MvcHtmlString hidden = helper.Hidden(name, value);
MvcHtmlString textBox = helper.TextBox(name + "_AutoComplete", text, viewhtmlAttributes);
var builder = new StringBuilder();
builder.AppendLine(hidden.ToHtmlString());
builder.AppendLine(textBox.ToHtmlString());
return new MvcHtmlString(builder.ToString());
}
}
}
部门模型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace AutoCompleteHelper_MVC.Models
{
public class Department
{
public int DepartmentID { get; set; }
public string DepartmentName { get; set; }
public static List<Department> TotalDepartments
{
get
{
return new List<Department>{
new Department{DepartmentID=1,DepartmentName="Accounts"},
new Department{DepartmentID=2,DepartmentName="Advertisement"},
new Department{DepartmentID=3,DepartmentName="Sales"},
new Department{DepartmentID=4,DepartmentName="Shipment"},
new Department{DepartmentID=5,DepartmentName="Production"},
new Department{DepartmentID=6,DepartmentName="Marketing"}
};
}
}
public static List<Department> GetDepartmentsLikeName(string namestring)
{
var x=TotalDepartments.Where<Department>(d=>d.DepartmentName.ToLower().StartsWith(namestring.ToLower()));
return x.ToList();
}
}
}
员工模型
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace AutoCompleteHelper_MVC.Models
{
public class Employee
{
public int EmployeeID { get; set; }
[Required]
public string EmployeeName { get; set; }
public static List<Employee> TotalEmployees
{
get
{
return new List<Employee>{
new Employee{EmployeeID=1,EmployeeName="Addison",DepartmentID=1},
new Employee{EmployeeID=2,EmployeeName="Ashwin",DepartmentID=1},
new Employee{EmployeeID=3,EmployeeName="Alden",DepartmentID=1},
new Employee{EmployeeID=4,EmployeeName="Anthony",DepartmentID=6},
new Employee{EmployeeID=5,EmployeeName="Bailee",DepartmentID=5},
new Employee{EmployeeID=6,EmployeeName="Baileigh",DepartmentID=4},
new Employee{EmployeeID=7,EmployeeName="Banjamin",DepartmentID=2},
new Employee{EmployeeID=8,EmployeeName="Cadan",DepartmentID=3},
new Employee{EmployeeID=9,EmployeeName="Cadimhe",DepartmentID=2},
new Employee{EmployeeID=10,EmployeeName="Carissa",DepartmentID=1},
new Employee{EmployeeID=11,EmployeeName="Ceara",DepartmentID=2},
new Employee{EmployeeID=12,EmployeeName="Cecilia",DepartmentID=1}
};
}
}
public int DepartmentID { get; set; }
public static List<Employee> GetEmployeesLikeName(string namestring)
{
var x = TotalEmployees.Where<Employee>(d => d.EmployeeName.ToLower().StartsWith(namestring.ToLower()));
return x.ToList();
}
}
}
测试控制器
using AutoCompleteHelper_MVC.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace AutoCompleteHelper_MVC.Controllers
{
public class TestAutoCompleteController : Controller
{
//
// GET: /AutoComplete/
public ActionResult Index()
{
var empObj = new Employee { EmployeeID = 1, EmployeeName = "Michale" };
return View(empObj);
}
public ActionResult GetEmployees(string searchHint)
{
return Json(Employee.GetEmployeesLikeName(searchHint),JsonRequestBehavior.AllowGet);
}
// GET: /AutoComplete/
public ActionResult GetDepartments(string searchHint)
{
return Json(Department.GetDepartmentsLikeName(searchHint), JsonRequestBehavior.AllowGet);
}
// GET: /AutoComplete/
public ActionResult GetGeneralItems(string searchHint)
{
return Json(Employee.GetEmployeesLikeName(searchHint), JsonRequestBehavior.AllowGet);
}
}
}
自定义自动完成javascript
//attached autocomplete widget to all the autocomplete controls
$(document).ready(function () {
BindAutoComplete();
});
function BindAutoComplete() {
$('[data-autocomplete]').each(function (index, element) {
var sourceurl = $(element).attr('data-sourceurl');
var autocompletetype = $(element).attr('data-autocompletetype');
$(element).autocomplete({
source: function (request, response) {
$.ajax({
url: sourceurl,
dataType: "json",
data: { searchHint: request.term },
success: function (data) {
response($.map(data, function (item) {
if (autocompletetype == 'none') {
return {
label: item.EmployeeName,
value: item.EmployeeName,
selectedValue: item.EmployeeID
};
}
else if (autocompletetype == 'department') {
return {
label: item.DepartmentName,
value: item.DepartmentName,
selectedValue: item.DepartmentID
};//
}
else if (autocompletetype == 'employee') {
return {
label: item.EmployeeName,
value: item.EmployeeName,
selectedValue: item.EmployeeID
};//
}
}));
},
error: function (data) {
alert(data);
},
});
},
select: function (event, ui) {
var valuetarget = $(this).attr('data-valuetarget');
$("input:hidden[name='" + valuetarget + "']").val(ui.item.selectedValue);
var selectfunc = $(this).attr('data-selectfunction');
if (selectfunc != null && selectfunc.length > 0) {
window[selectfunc](event, ui);
}
},
change: function (event, ui) {
var valuetarget = $(this).attr('data-valuetarget');
$("input:hidden[name='" + valuetarget + "']").val('');
},
});
});
}