多对多关系弹出

时间:2016-06-06 05:47:46

标签: model-view-controller asp.net-mvc-5 asp.net-mvc-partialview

基本上从嵌入式领域和新的MVC / ASP.net,学习。

我有2个具有多对多关系的实体。 它工作正常,我可以分配关系下注

标题

使用复选框进行操作。

enter image description here

我想实现以下内容:

实体1 的创建页面上,相对实体2 列表显示在链接取消链接的表格中的按钮。

查找以下图片: enter image description here

链接按钮会打开弹出窗口,其中会显示与实体1 关系不存在的实体2 列表。< / p>

enter image description here 用户将使用复选框选择所需的实体2 ,然后按“提交按钮。

在按提交按钮时,所选的实体2 对象将添加到“创建”视图中的**实体2 **表中,并且弹出窗口将关闭。

在保存创建视图时,将保存关系中的所有内容。

我希望我不要求太多......不能判断。

提前致谢。

1 个答案:

答案 0 :(得分:0)

已经工作: 1)我能够使用bootstrap模式弹出方法打开模型,并将实体2列表传递给它。 2.)我能够在表格中显示列表。

实现: 1)在弹出视图中填充实体2 列表,其中的对象不在主视图中的实体2 表中。

2)在弹出表中选中复选框以供选择。

3)将所选的实体2 行详细信息获取到主视图,而不发布到控制器。

4)使用选定的行更新主视图中的实体2 表。

5)按下保存按钮时保存到表格..

实体1:

public partial class JobPost
{
    public JobPost()
    {
        this.JobTags = new HashSet<JobTag>();
    }

    public int JobPostId { get; set; } 
    public string Title { get; set; }

    public virtual ICollection<JobTag> JobTags { get; set; }
}

实体2:

public partial class JobTag
{
    public JobTag()
    {
        this.JobPosts = new HashSet<JobPost>();
    }

    public int JobTagId { get; set; } 
    public string Tag { get; set; }

    public virtual ICollection<JobPost> JobPosts { get; set; }
}

public class TempJobTag 
{
    public int JobTagId { get; set; }
    public string Tag { get; set; }
    public bool isSelected { get; set; } 
}

查看型号:

public class JobPostViewModel
{
    public JobPost JobPost { get; set; }
    public IEnumerable<SelectListItem> AllJobTags { get; set; }

    private List<int> _selectedJobTags;
    public List<int> SelectedJobTags
    {
        get
        {
            if (_selectedJobTags == null)
            {
                _selectedJobTags = JobPost.JobTags.Select(m => m.JobTagId).ToList();
            }
            return _selectedJobTags;
        }
        set { _selectedJobTags = value; }
    }
}

实体1控制器:

// GET: JobPosts/Create
    public ActionResult Create()
    {
        var jobPostViewModel = new JobPostViewModel
        {
            JobPost = new JobPost(),
        };

        if (jobPostViewModel.JobPost == null)
            return HttpNotFound();

        var allJobTagsList = db.JobTags.ToList();
        jobPostViewModel.AllJobTags = allJobTagsList.Select(o => new SelectListItem
        {
            Text = o.Tag,
            Value = o.JobTagId.ToString()
        });

        return View(jobPostViewModel);
    }

    // POST: JobPosts/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(JobPostViewModel jobpostView)
    {
        if (ModelState.IsValid)
        {
            var newJobTags = db.JobTags.Where(
                    m => jobpostView.SelectedJobTags.Contains(m.JobTagId)).ToList();
            var updatedJobTags = new HashSet<int>(jobpostView.SelectedJobTags);

            foreach (JobTag jobTag in db.JobTags)
            {
                if (!updatedJobTags.Contains(jobTag.JobTagId))
                {
                    jobpostView.JobPost.JobTags.Remove(jobTag);
                }
                else
                {
                    jobpostView.JobPost.JobTags.Add((jobTag));
                }
            }

            db.JobPosts.Add(jobpostView.JobPost);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(jobpostView);
    }

    public ActionResult ViewJobPostTagPopUp()  
    {
        var allJobTagsList = db.JobTags.ToList();

        foreach (JobTag jobTag in db.JobTags)
        {
            if (jobTag.JobTagId == 1)
            {
                allJobTagsList.Remove(jobTag);
            }
        }

        List<TempJobTag> tmpJobTags = new List<TempJobTag>();

        foreach (JobTag jobTag in db.JobTags)
        {
            TempJobTag tmpJT = new TempJobTag();
            tmpJT.Tag = jobTag.Tag;
            tmpJT.JobTagId = jobTag.JobTagId;
            tmpJobTags.Add(tmpJT);
        }

        return PartialView("JobTagIndex", tmpJobTags);
    }

    [HttpPost]
    //[ValidateAntiForgeryToken]
    public JsonResult ViewJobPostTagPopUp(List<TempJobTag> data)       
    {
        if (ModelState.IsValid)
        {
        }

        return Json(new { success = true, message = "Some message" });
    }

主要观点:

@model MVCApp20.ViewModels.JobPostViewModel

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

<h2>Create</h2>

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

<div class="form-horizontal">
    <h4>JobPost</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.JobPost.Title, htmlAttributes: new     { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.JobPost.Title, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.JobPost.Title, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.AllJobTags, "JobTag", new { @class  = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.ListBoxFor(m => m.SelectedJobTags, Model.AllJobTags)
        </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("+", "ViewJobPostTagPopUp", "JobPosts",
null, new { @class = "modal-link btn btn-success" })
</div>

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

<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>

  <script type="text/javascript">

</script>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}

部分弹出视图:

@model IEnumerable<MVCApp20.Models.TempJobTag>
@{
ViewBag.Title = "Index";
//Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>Tags</h2>

@using (Html.BeginForm())
{
<table id="datatable" class="table">
    <tr>
        <th>
            <input type="checkbox" id="checkAll" />
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Tag)
        </th>
        <th></th>
    </tr>
    @foreach (var item in Model)
    {
        <tr>
            <td>
                @*@Html.EditorFor(modelItem => item.isSelected)*@
                <input type="checkbox" class="checkBox"
                       value="@item.isSelected" />
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Tag)
            </td>
        </tr>
    }
</table>
@*<div>
    @Html.ActionLink("Done", "ViewJobPostTagPopUp", "JobPosts",
    null, new { @class = "modal-link btn btn-primary" })
</div>*@

<div>
    <button type="submit" id="btnSubmit" class=" btn  btn-primary">Submit</button>
</div>
}

<script>
$(document).ready(function () {

    $("#checkAll").click(function () {
        $(".checkBox").prop('checked',
            $(this).prop('checked'));
    });
});

$(function () {
    $('#btnSubmit').click(function () {
        var sdata = new Array();
        sdata = getSelectedIDs();
        var postData = {};
        postData[values] = sdata;

        $.ajax({
            url: '@Url.Action("ViewJobPostTagPopUp")',
            type: "POST",
            type: this.method,
            //data: $(this).serialize(),
            data: JSON.stringify(product),

            success: function (result) {
                alert("success");
            },
            fail: function (result) {
                alert("fail");
            }
        });

        //alert("hiding");
        //$('#modal-container').modal('hide');
    });
});

function getSelectedIDs() {
    var selectedIDs = new Array();
    var i = 0;
    $('input:checkbox.checkBox').each(function () {
        if ($(this).prop('checked')) {
            selectedIDs.push($(this).val());
            i++;
            alert("got" + i);
        }
    });

    return selectedIDs;
}
</script>