如何根据该外键对象的自动完成选择创建新的数据库条目并填充外键?

时间:2017-01-30 04:25:14

标签: asp.net-mvc entity-framework

我正在开发一个ASP.NET MVC应用程序,并且有一个包含序列号模型的外键的修复模型。在我看来,我有一个预先类型的jquery在数据库中进行自动完成搜索,以允许用户选择数据库中已有的序列号。然后,我有字段填写将填充修复表的新信息。我似乎无法从所选序列号中获取所选的SerialNumber.Id以填充Repair.SerialNumber_Id。

我的观点:

@model EntityTestApp.Models.Repair

@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Create</h2>

@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>Repair</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.RepairDate, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.RepairDate, new {htmlAttributes = new { @class = "form-control", @Value = DateTime.Now.ToShortDateString() } })
                @Html.ValidationMessageFor(model => model.RepairDate, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.SerialNumber, htmlAttributes: new { @class = "control-label col-md-2"})
            <div class="col-md-10">
              <input id="serialNumberTextBox" type="text" value="" class="form-control" />
                 @Html.ValidationMessageFor(model => model.SerialNumber, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.CustomerComplaint, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextAreaFor(model => model.CustomerComplaint, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.CustomerComplaint, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.IssueFound, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextAreaFor(model => model.IssueFound, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.IssueFound, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.RepairActionTaken, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextAreaFor(model => model.RepairActionTaken, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.RepairActionTaken, "", new { @class = "text-danger" })
            </div>
        </div>


        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section scripts{
<script>


    $(document).ready(function () {


        var SerialNumbers = new Bloodhound({
            datumTokenizer: Bloodhound.tokenizers.obj.whitespace('Number'),
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            remote: {
                url: '/api/serialnumbers?query=%QUERY',
                wildcard: '%QUERY'
            }
        });

        $('#serialNumberTextBox').typeahead({

            highlight: true
        }, {
            name: 'SerialNumbers',
            display: 'Number',
            source: SerialNumbers
        }).on("typeahead:select", function (e, SerialNumber) {

            //alert(serialNumberTextBox.value)

        });

    });


    </script>    
}

我的Controller操作来创建一个新的修复条目:

// GET: Repairs/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Repairs/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]

        public ActionResult Create(Repair repair)
        {
            if (ModelState.IsValid)
            {

                db.Repairs.Add(repair);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(repair);
        }

我的修理模型:

public class Repair
{

    public int Id { get; set; }
    [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime RepairDate { get; set; }
    public SerialNumber SerialNumber { get; set; }

    public string CustomerComplaint { get; set; }
    public string IssueFound { get; set; }
    public string RepairActionTaken { get; set; }


}

1 个答案:

答案 0 :(得分:0)

好的,几个晚上拉头发后我发现了。我必须添加一个隐藏字段来保存外键的值,并根据&#39; typeahead&#39;分配该值。使用&#34; document.getElementById(&#39;&#39;)进行javascript自动填充选择。

像魅力一样工作。谢谢你的帮助!

-Chris