有创建联系人的视图
@using (Html.BeginForm("Create", "Contact", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>Добавить контакт</legend>
<div class="editor-label">Surname</div>
<div class="editor-field">
@Html.EditorFor(model => model.Surname)
@Html.ValidationMessageFor(model => model.Surname)
</div>
<div class="editor-label">Name</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">Отчество</div>
<div class="editor-field">
@Html.EditorFor(model => model.MiddleName)
@Html.ValidationMessageFor(model => model.MiddleName)
</div>
<div class="editor-label">Phone</div>
<div class="editor-field">
@Html.EditorFor(model => model.Phone)
@Html.ValidationMessageFor(model => model.Phone)
</div>
<div class="editor-label">E-mail</div>
<div class="editor-field">
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<div class="editor-label">Image</div>
<div class="editor-field">
<input type="file" name="uploadImage" />
</div>
<p>Company:</p>
<input type="text" name="name" data-autocomplete-source='@Url.Action("GetSearchValue", "Company")' />
<p>
<input type="submit" value="Create" />
</p>
}
公司使用Ajax自动完成
<script type="text/javascript">
$(function () {
$("[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({ source: target.attr("data-autocomplete-source") });
});
});
public ActionResult GetSearchValue(string term)
{
var models = db.Companies.Where(x => x.Name.Contains(term))
.Select(a => new
{
Id = a.Id.ToString(),
value = a.Name,
label = a.Name
}).ToList();
return Json(models, JsonRequestBehavior.AllowGet);
}
未显示创建联系人页面上的Id公司。如何在Contact控制器方法中创建具有公司ID(一对多)值的联系人? [![在此处输入图像说明] [1]] [1]
控制器联系和型号联系
public ActionResult Create(Contact contact, HttpPostedFileBase uploadImage)
{
if (User.Identity.IsAuthenticated)
{
if (ModelState.IsValid && uploadImage != null)
{
byte[] imageData = null;
// считываем переданный файл в массив байтов
using (var binaryReader = new BinaryReader(uploadImage.InputStream))
{
imageData = binaryReader.ReadBytes(uploadImage.ContentLength);
}
// установка массива байтов
contact.Image = imageData;
contact.ImageMimeType = uploadImage.ContentType;//DELETE
db.Contacts.Add(contact);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(contact);
}
else
{
return RedirectToAction("Login", "Account");
}
}
public class Contact
{
public int ID { get; set; }
[Display(Name="Фамилия")]
public string Surname { get; set; }
[Display(Name="Имя"), Required]
public string Name { get; set; }
[Display(Name = "Отчество")]
public string MiddleName { get; set; }
[Display(Name="Email")]
public string Email { get; set; }
[RegularExpression("\\+380+\\d+", ErrorMessage="Введите номер в фортмате +380ХХХХХХХХХ")]
[Display(Name = "Телефон"), MaxLength(13), Required]
public string Phone { get; set; }
[Display(Name = "Фото профиля")]
public byte[] Image { get; set; }
public string ImageMimeType { get; set; }
public int? CompanyId { get; set; }
public virtual Company Companies { get; set; }
}
如何使用ajax自动完成功能在db中保存CompanyId 怎么写输入名称公司? [
答案 0 :(得分:0)
不是使用输入字段绑定公司详细信息,而是将获取的公司详细信息与下拉列表绑定,其中值为公司标识,在您的情况下,a.Id和名称或标签是公司名称,a.Name是您的情况。
在这种情况下,用户将获得一个选项,从下拉列表中选择公司,当数据发回服务器时,您将在控制器中收到公司ID,而不是公司名称。
如果您希望用户拥有搜索功能,您可以在下拉列表顶部实现该功能。
我希望这会有所帮助。
答案 1 :(得分:0)
首先,您需要在剃刀中添加隐藏字段。该隐藏字段应存储所选公司的Id
:
// I suppose that you have a property named CompanyId in your view model.
@Html.HiddenFor(model => model.CompanyId, new { data_company_id = string.Empty })
在您的javascript中,您需要告诉jQuery autocomplete
小部件存储所选公司Id
的位置。因此,您需要通过处理select
小部件的autocomplete
事件来执行此操作:
$("[data-autocomplete-source]").each(function () {
var target = $(this);
target.autocomplete({
source: target.attr("data-autocomplete-source"),
select: function( event, ui ) {
$('input[data-company-id]').val(ui.item.value);
$('input[name="name"]').val(ui.item.label);
}
});
});
在您需要将公司Id存储到返回的json对象的value属性之前,如下所示:
public ActionResult GetSearchValue(string term)
{
var models = db.Companies.Where(x => x.Name.Contains(term))
.Select(a => new
{
value = a.Id.ToString(), // <- this need to be done
label = a.Name
}).ToList();
return Json(models, JsonRequestBehavior.AllowGet);
}
之后,您的Create
操作将包含所选公司Id
。