gpt4 book ai didi

jquery - 将 TokenInput 和 razor 代码绑定(bind)到同一模型?

转载 作者:行者123 更新时间:2023-12-01 03:18:48 26 4
gpt4 key购买 nike

在 HTML 表单中,如何像将普通基本类型绑定(bind)到模型一样绑定(bind) jquery 控件(例如 tokeninput)?我正在努力寻找方法来做到这一点,我知道你可以使用自定义模板等,但没有任何 jquery 插件。

具体来说,我正在使用 tokenInput 请参阅此处 ( http://loopj.com/jquery-tokeninput/ )。下面是我针对标准 HTML 文本输入应用的 jQuery 代码。对于每次按键,它都会发送到 Controller 以返回作者列表。您还可以预填充作者,我使用 HTML5 中的数据标记来预填充控件。

 $("#AUTHORs").tokenInput('/author/getauthors/', {
hintText: "Enter surname",
searchingText: "Searching...",
preventDuplicates: true,
allowCustomEntry: true,
highlightDuplicates: false,
tokenDelimiter: "*",
resultsLimit: 10,
theme: "facebook",
prePopulate: $('#AUTHORs').data('AUTHORs')
});

我从我的角度发布了一些代码,只是为了向您展示我试图绑定(bind)到模型的内容。

@model myModels.BOOK

@{
ViewBag.Title = "Edit";
}

@using (Html.BeginForm()) {
@Html.ValidationSummary(true)
<fieldset>
<legend>Basic</legend>

<div class="editor-label">
@Html.LabelFor(model => model.TITLE)
</div>
<div class="editor-field" >
@Html.EditorFor(model => model.TITLE)
@Html.ValidationMessageFor(model => model.TITLE)
</div>
<div class="authors">
<div class="editor-field">
<input type="text" id="authors" name="authors" data-val="true" data-val-required="You must enter at least one author" data-authors="@Json.Encode(Model.AUTHORs.Select(a => new { id = a.AUTHOR_ID, name = a.FULL_NAME }))"/>
<span class="field-validation-valid" data-valmsg-for="authors" data-valmsg-replace="true"></span>
</div>
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}

这是我在尝试更新表单上的模型(按“保存”后)时使用的代码:

  [HttpPost]
public ActionResult Edit(BOOK book)
{
if (ModelState.IsValid)
{
db.Entry(book).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Details", new { id = book.REF_ID });
}
ViewBag.REF_ID = new SelectList(db.REFERENCEs, "REF_ID", "REF_ID", book.REF_ID);
return View(book);
}
<小时/>

当您查看 HTML 中的代码时,它已根据 tokeninput 元素对作者进行了格式化,看起来像这样,而且我认为这种格式确实存在问题:

<input type="text" id="AUTHORs" name="AUTHORs" data-val="true" data-val-required="You must enter at least one author" data-authors="

[{&quot;id&quot;:156787,&quot;name&quot;:&quot;Faure,M.&quot;},

{&quot;id&quot;:177433,&quot;name&quot;:&quot;Wang,D.Z.&quot;},

{&quot;id&quot;:177434,&quot;name&quot;:&quot;Shu,L.Sh&quot;},

{&quot;id&quot;:177435,&quot;name&quot;:&quot;Sheng,W.Z.&quot;}]"

style="display: none; ">

最佳答案

您似乎正在使用 tokeninput plugin 。让我们通过一个分步示例来了解如何使用 ASP.NET MVC 来实现这一点:

型号:

public class Book
{
public string Title { get; set; }
public IEnumerable<Author> Authors { get; set; }
}

public class Author
{
public int Id { get; set; }
public string Name { get; set; }
}

Controller :

public class HomeController : Controller
{
// fake a database. Obviously that in your actual application
// this information will be coming from a database or something
public readonly static Dictionary<int, string> Authors = new Dictionary<int, string>
{
{ 1, "foo" },
{ 2, "bar" },
{ 3, "baz" },
{ 4, "bazinga" },
};

public ActionResult Index()
{
// preinitialize the model with some values => obviously in your
// real application those will be coming from a database or something
var model = new Book
{
Title = "some title",
Authors = new[]
{
new Author { Id = 2, Name = "bar" }
}
};
return View(model);
}

[HttpPost]
public ActionResult Index(Book book)
{
return Content(string.Format("thanks for selecting authors: {0}", string.Join(" ", book.Authors.Select(x => x.Name))));
}

public ActionResult GetAuthors(string q)
{
var authors = Authors.Select(x => new
{
id = x.Key,
name = x.Value
});
return Json(authors, JsonRequestBehavior.AllowGet);
}
}

查看:

@model Book
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(x => x.Title)
@Html.EditorFor(x => x.Title)
</div>
<div>
@Html.TextBoxFor(
x => x.Authors,
new {
id = "authors",
data_url = Url.Action("GetAuthors", "Home"),
data_authors = Json.Encode(
Model.Authors.Select(
x => new { id = x.Id, name = x.Name }
)
)
}
)
</div>
<button type="submit">OK</button>
}

<script type="text/javascript" src="@Url.Content("~/scripts/jquery.tokeninput.js")"></script>
<script type="text/javascript">
var authors = $('#authors');
authors.tokenInput(authors.data('url'), {
hintText: 'Enter surname',
searchingText: 'Searching...',
preventDuplicates: true,
allowCustomEntry: true,
highlightDuplicates: false,
tokenDelimiter: '*',
resultsLimit: 10,
theme: 'facebook',
prePopulate: authors.data('authors')
});
</script>

最后一步是编写一个自定义模型绑定(bind)器,它将从 ID 中检索作者:

public class AuthorModelBinder : IModelBinder
{
public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var values = bindingContext.ValueProvider.GetValue(bindingContext.ModelName);
if (values != null)
{
// We have specified asterisk (*) as a token delimiter. So
// the ids will be separated by *. For example "2*3*5"
var ids = values.AttemptedValue.Split('*').Select(int.Parse);

// Now that we have the selected ids we could fetch the corresponding
// authors from our datasource
var authors = HomeController.Authors.Where(x => ids.Contains(x.Key)).Select(x => new Author
{
Id = x.Key,
Name = x.Value
}).ToList();
return authors;
}
return Enumerable.Empty<Author>();
}
}

将在Application_Start中注册:

ModelBinders.Binders.Add(typeof(IEnumerable<Author>), new AuthorModelBinder());

关于jquery - 将 TokenInput 和 razor 代码绑定(bind)到同一模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12510797/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com