ASP.NET MVC5,JSON,popup partialView - 设置DropDownList选中

时间:2015-05-29 17:05:56

标签: javascript c# json asp.net-mvc

我想设置DDL所选项目,并在弹出页面中插入项目。 使用过的脚本示例 - http://www.advancesharp.com/blog/1126/search-sort-paging-insert-update-and-delete-with-asp-net-mvc-and-bootstrap-modal-popup-part-2

在JsonResult中,我看到插入的值(使用断点检查调试模式),但需要帮助,在主页的DDL中将此值设置为选中。

public ActionResult WorkPlaces(int id = 0)
        {
            var workPlace = new Work();
            return PartialView("WorkPlaces", workPlace);
        }
[HttpPost]
public JsonResult WorkPlaces(Work work)
{
    if (ModelState.IsValid)
    {
       db.Works.Add(work);
       db.SaveChanges();
       return Json(new { success = true });
    }
       return Json(work, JsonRequestBehavior.AllowGet);
}

模型类

public class Person
{
    public int Id { get; set; }
    [Display(Name = "Person Name")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Name is required")]
    public string Name { get; set; }
    public Nullable<int> WorkId { get; set; }
    public virtual Work Work { get; set; }
}

public class Work
{
    public int Id { get; set; }
    [Display(Name = "Work place")]
    [Required(AllowEmptyStrings = false, ErrorMessage = "Name is required")]
    public string workPlace { get; set; }
}

主页

    @model testAppAuth.Models.Person

    @{
        ViewBag.Title = "Create";
    }

    <h2>Create</h2>


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

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

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

                <a class="btn btn-success" data-modal="" href="/Person/WorkPlaces" id="btnCreate">
                    <span class="glyphicon glyphicon-plus"></span>
                </a>
            </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>

    <!-- modal placeholder-->
    <div id='myModal' class='modal fade in'>
        <div class="modal-dialog">
            <div class="modal-content">
                <div id='myModalContent'></div>
            </div>
        </div>
    </div>
    @section scripts{
        @Scripts.Render("~/Scripts/Appjs/WorkPlace.js")
    }

弹出页面

    @model testAppAuth.Models.Work

    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 class="modal-title">Add new workplace</h3>
    </div>
    @using (Html.BeginForm())
    {
        @Html.AntiForgeryToken()

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

        </div>

    <div class="modal-footer">
        <span id="progress" class="text-center" style="display: none;">
            <img src="/images/wait.gif" alt="wiat" />
            Wait..
        </span>

        <input class="btn btn-primary" type="submit" value="Save" />
        <button class="btn btn-warning" data-dismiss="modal">Close</button>
    </div>
    }


<script>
        $("form").removeData("validator");
        $("form").removeData("unobtrusiveValidation");
        $.validator.unobtrusive.parse("form");
</script>
用于弹出窗口的

脚本

$(function () {
    $.ajaxSetup({ cache: false });
    $("a[data-modal]").on("click", function (e) {
        $('#myModalContent').load(this.href, function () {
            $('#myModal').modal({
                keyboard: true
            }, 'show');
            bindForm(this);
        });
        return false;
    });
});

function bindForm(dialog) {
    $('form', dialog).submit(function () {
        $('#progress').show();
        $.ajax({
            url: this.action,
            type: this.method,
            data: $(this).serialize(),
            success: function (result) {
                if (result.success) {
                    $('#myModal').modal('hide');
                    $('#progress').hide();
                    location.reload();
                } else {
                    $('#progress').hide();
                    $('#myModalContent').html(result);
                    bindForm();
                }
            }
        });
        return false;
    });
}

此外,使用此脚本甚至我在Model类中设置[Required]属性,如果我单击关闭按钮而不填充字段,它将关闭。如何让它不要关闭?

2 个答案:

答案 0 :(得分:1)

你的第一个问题:

您可以使用Jquery执行此操作:

关闭对话框时(Sucess)对一个函数进行Jquery调用,该函数将获取提交的值并更改主页面中的选定项目。

例如:

 $('form', dialog).submit(function () {
if(isValidInput()){           
 $('#progress').show();

   //make Ajax Call

  }

});

function IsValidInput(){
//do validation
}

你的第二个问题:

Ajax Call不关心模型验证。

当您从模态提交数据时,请在进行AJAX调用之前验证所需字段的值。

离。

var opt = {"class":"my-class", "type": "checkbox", "checked":"checked"};

Object.keys(opt).forEach( function(key){ input.setAttribute(key,opt[key]); } );

答案 1 :(得分:0)

关于如何在关闭模型之前验证的问题,请使用以下代码

$(function () {


$('#myModal').on('hide.bs.modal', function (event) {
    var form = $("#formid");
    form.Validate();
    if(form.Valid()){
    //Ajax;
    }
    else{
    event.PreventDefault();
    }})});

现在在ajax中成功使用jquery为DropDown添加值