ASP.NET MVC : Save multiple values on autocomplete

标签 asp.net mysql asp.net-mvc many-to-many

我有一个 mysql 数据库,其中包含表“deliverables”、“tags”和“deliverables_has_tags”。我想将标签链接到可交付成果。

这是我在 javascript 文件中所做的:

<script type="text/javascript" language="javascript">
    $(function () {
        var object = {};
        $.ajax({
            type: "GET",
            url: "/Deliverable/Tags",
            dataType: "json",
            success: function (data) {
                object.tags = data;
            }
        });

        function split(val) {
            return val.split(/,\s*/);
        }
        function extractLast(term) {
            return split(term).pop();
        }
        $("#tags")
        // don't navigate away from the field on tab when selecting an item
            .bind("keydown", function (event) {
                if (event.keyCode === $.ui.keyCode.TAB &&
                $(this).data("ui-autocomplete").menu.active) {
                    event.preventDefault();
                }
            })

.autocomplete({
    minLength: 0,
    source: function (request, response) {
        // delegate back to autocomplete, but extract the last term
        response($.ui.autocomplete.filter(
object.tags, extractLast(request.term)));
    },
    focus: function () {
        // prevent value inserted on focus
        return false;
    },
    select: function (event, ui) {
        var terms = split(this.value);
        // remove the current input
        terms.pop();
        // add the selected item
        terms.push(ui.item.value);
        // add placeholder to get the comma-and-space at the end
        terms.push("");
        this.value = terms.join(", ");

        return false;
    }
});
    });
</script>

我可以在文本框中添加多个标签。

但现在我想将其保存在我的存储库中。 在 Controller 中的 Action 方法中:

repository.AddDeliverable(model.Title, model.Description, model.UsernameID, data, datatwo, model.VideoUrl, model.AfstudeerrichtingID, model.ProjectID);

标签操作:

public JsonResult Tags()
{
    var data = (repository.GetTags()).ToArray();

    return Json(data, JsonRequestBehavior.AllowGet);
}

在我的仓库中:

public IQueryable<string> GetTags()
{
    return from tag in entities.tags
           orderby tag.tag_name
           select tag.tag_name;
}

我不知道如何将其保存在我的数据库中。
谁能帮帮我?

最佳答案

如果我正确理解了您的问题,那么您已经按如下方式实现了标签处理:

  1. 有一个 MVC 操作方法返回带有不包含数据的输入占位符的 View
  2. 占位符本身可能是 input type=text with id=tags
  3. 在“dom ready”时,您触发 ajax 请求以从数据库中检索您的标签,json 序列化为数组;当它到达时,你将它存储到 tags 变量(没有错误处理(!))
  4. 同时,您使用 jqueryui 自动完成功能装饰您的输入,该自动完成功能对用户输入作出 react 并从标签变量返回项目
  5. 由于输入已经包含标签(逗号分隔),您的过滤器是最后一个标签的第一个字母

所以,当用户输入了几个逗号分隔的标签(可能其中一些可能是新的)并且现在想将其保存到数据库时,您会遇到这种情况。对于每个输入,如果这是一个已知标签,则必须将其存储到“deliverables_has_tags”。如果有新标签,则必须将其同时存储到“tags”和“deliverables_has_tags”。

最常见的情况是使用“保存”按钮开始保存过程。 让我们分析一下您在此过程中必须执行的操作。

1) 按钮点击

On button click you use js to convert your comma separated tags string using logic like split(term) to the array, and serialize it. You can do serialization using serializeArray and manually create JSON object, or serialize the whole form using $('#yourForm').serialize(). I would choose the first option because that way I get more control over JSON format and avoid problems with MVC default model binder.

2) Ajax调用

When the JSON object is ready to be sent, you fire an ajax POST request to your MVC POST action method. When you save state always avoid GET because new versions of browsers can scan thru your page and actively preload urls using GET requests. You don't want this here. Of course, use your data as a data-parameter in the ajax call.

3) Action 方法

When the request arrives, you have to process it in your controller using a new action method. Typically in this case you will have something like public JsonResult SaveTags(SaveTagsModel saveTags) { ... } which saves tags using your repository and returns result that says something like 'OK' or 'ERROR' (sth like response.isSaved=true/false). Tricky part can be designing view model according to your JSON object - this could help. And regarding collections this could be valuable info.

When saving, use transaction to ensure everything is saved at once. First check if each tag exists in the database and insert those who don't exist. After that, check for each tag if there is appropriate n-n relation in deliverables_has_tags and insert it if there isn't. I believe that you should use same repository encapsulation for both operations.

关于ASP.NET MVC : Save multiple values on autocomplete,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16924024/

相关文章:

mysql - 如何在SQL中重置wp_posts ID表?

mysql - DATE_SUB() 总是返回 0 个结果

c# - MVC Controller : Common object in methods

javascript - 从 Razor 输出 JavaScript

asp.net - GridView 固定标题 CSS 对齐

asp.net - 不支持每种类型多个对象集。对象集 'ApplicationUsers'和 'Users'都可以包含ApplicationUser类型的实例

c# - 有没有办法预览服务器上存储的文档?

mysql - 如何使用内部查询优化mysql查询

asp.net-mvc - 将 razor View 渲染为字符串而不修改 html

asp.net - 对于 asp.net 中的 session 状态模式,InProc 或 SQL Server 哪个更好?