如何将模态提交给控制器并在编辑模式对话框关闭后刷新ajax

时间:2013-12-25 23:49:09

标签: jquery ajax asp.net-mvc-4

以下是我的情景:

我正在使用uikit在主页中显示如下对话框:

<div id="modalEdit" class="uk-modal">
    <div class="uk-modal-dialog uk-modal-dialog-slide">
        <a href="" class="uk-modal-close uk-close"></a>
    </div>
</div>

当用户点击它时,它会显示员工列表。

<div class="category">
            <span><a class="mainLink" data-url="@Url.Action("Index","Employee",  new {Area="Application"})" href="javascript:void(0);">Employee</a> </span>

            <div class="subCategory">

                <a href="#modalEdit" data-uk-modal onclick="editEmployee()"></a>
            </div>
            <a class="expand"><img src="~/Images/down-arrow.png" /></a>
</div>

<script>
$('.mainLink').click(function() {
        var a = $(this);

        var link = a.attr('data-url');

        if (link.length > 0)
            {

        $.ajax({
            url: link,

            success: function(data) {
                $('#output').html(data);
            },

            error: function(data) {
                $('#output').html("<h2> No results found</h2>");
            }
        });
        }
    });
</script>

这是我用于编辑模态的cshtml文件。

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

    <fieldset>
        <legend>EmployeeViewModel</legend>

        @Html.HiddenFor(model => model.EmployeeId, new {id="employeeId"})

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.FirstName, new {id="employeeFirstName"})
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.MiddleName)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.MiddleName, new {id="employeeMiddleName"})
            @Html.ValidationMessageFor(model => model.MiddleName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.LastName, new {id="employeeLastName"})
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <p>
            <input type="submit" data-url="@Url.Action("Edit", "Employee", new { Area = "Application" })" value="Save"/>
        </p>
    </fieldset>
}

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

<script>
    $('form').submit(function() {
        var $form = $(this);
        //alert($('#employeeId').val());
        $.ajax({
            type: "Post",
            url: $form.attr('data-url'),
            data: {
                EmployeeId: $('#employeeId').val(),
                FirstName: $('#employeeFirstName').val(),
                MiddleName: $('#employeeMiddleName').val(),
                LastName: $('#employeeLastName').val()
            },
            success: function (data) {
                $('#modalEdit').hide('slow');
                loadEmployee();
                //alert(data);
            },
            error: function(data) {
                alert("failed " + data);
            }
        });

        return false;
    });

    function loadEmployee() {
        //alert("hi");
        $.ajax({
            url: 'Application/Employee/Index',

            success: function (data) {
                //alert(data);
                $('#output').html(data);
            }
        });

    }
</script>

当用户在模态对话框中编辑时,数据应该发送到控制器:

//
// GET: /Application/Employee/Edit/5

public ActionResult Edit(int id = 0)
{
    EmployeeVm employeeviewmodel =new EmployeeVm(id);
    if (employeeviewmodel.EmployeeId<1)
    {
        return HttpNotFound();
    }
    return View(employeeviewmodel);
}

//
// POST: /Application/Employee/Edit/5

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit(EmployeeVm employeeviewmodel)
{
    if (ModelState.IsValid)
    {
        EmployeeEditVm employee=new EmployeeEditVm(employeeviewmodel);
        return RedirectToAction("Index");
    }
    return View(employeeviewmodel);
}

然后,模态对话框应关闭并更新主页员工数据。

我的观点:

public class EmployeeVm : ConventionInjection
    {
        private StringBuilder stringBuilder;

        public EmployeeVm(Employee employee)
        {
            this.InjectFrom<Employee>(employee);
        }

        public EmployeeVm(int id)
            : this(new Context().Employees.Find(id))
        {

        }

        public EmployeeVm()
        {

        }

        public int EmployeeId { get; set; }

        [Display(Name = "First Name")]
        [Required(ErrorMessage = "Pleae enter First Name"), StringLength(50)]
        public string FirstName { get; set; }

        [Display(Name = "Middle Name"), StringLength(50)]
        public string MiddleName { get; set; }

        [Display(Name = "Last Name"), StringLength(50)]
        [Required(ErrorMessage = "Please enter Last Name")]
        public string LastName { get; set; }

        public string FullName()
        {
            stringBuilder = new StringBuilder();
            stringBuilder.Append("<b>");
            stringBuilder.Append(LastName.ToUpper());
            stringBuilder.Append("</b>");
            if (!string.IsNullOrEmpty(MiddleName))
            {
                stringBuilder.Append(", ");
                stringBuilder.Append(MiddleName);
            }
            stringBuilder.Append(", ");
            stringBuilder.Append(FirstName);
            return stringBuilder.ToString();
        } 

        protected override bool Match(ConventionInfo c)
        {

            bool isMatch=((c.SourceProp.Name == "EmployeeId" && c.TargetProp.Name == "PersonId") ||
                    (c.SourceProp.Name == c.TargetProp.Name && c.SourceProp.Type==c.TargetProp.Type));
            return isMatch;
        }
    }

虽然,我已经显示了整个cshtml页面用于编辑,同名页面和视图模式,但它只是jquery / ajax不能正常工作。所有其他代码都经过测试并且工作正常。

这是我的问题: 那么,一旦模态对话框关闭,我怎样才能将数据传递给控制器​​并刷新员工列表?

Thanx提前给所有观众,也帮助我。

2 个答案:

答案 0 :(得分:2)

stringify只是将它转换为json,它不会将其转换为模型。由于您的ajax呼叫已经

EmployeeId: $('#employeeId').val(),
FirstName: $('#employeeFirstName').val(),
MiddleName: $('#employeeMiddleName').val(),
LastName: $('#employeeLastName').val()

您需要将控制器更改为

public ActionResult Edit(int EmployeeId, string FirstName, string MiddleName, string LastName){
    //do something with the data
}

如果要将对象传递回控制器,则需要执行类似

的操作
var employeeviewmodel = {};
employeeviewmodel.EmployeeId = $('#employeeId').val();
employeeviewmodel.FirstName = $('#employeeFirstName').val();
employeeviewmodel.MiddleName = $('#employeeMiddleName').val();
employeeviewmodel.LastName = $('#employeeLastName').val();

然后在你的ajax调用中字符串化employeeviewmodel。您在视图侧定义的名称必须与您在控制器端查找的内容完全匹配

答案 1 :(得分:1)

问题解决后我的最终代码(只需要修改这段代码):

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

   <fieldset>
        <legend>EmployeeViewModel</legend>

        @Html.HiddenFor(model => model.EmployeeId)

        <div class="editor-label">
            @Html.LabelFor(model => model.FirstName)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.FirstName)
            @Html.ValidationMessageFor(model => model.FirstName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.MiddleName)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.MiddleName)
            @Html.ValidationMessageFor(model => model.MiddleName)
        </div>

        <div class="editor-label">
            @Html.LabelFor(model => model.LastName)
        </div>
        <div class="editor-field">
            @Html.TextBoxFor(model => model.LastName)
            @Html.ValidationMessageFor(model => model.LastName)
        </div>

        <p>
            <input type="submit" id="Save"  value="Save"/>
        </p>
    </fieldset>
}

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

<script>

    $('#Save').click(function(event) {

        event.preventDefault();
        var data = $(this).closest('form').serialize();

        $.ajax({
            url: '/Application/Employee/Edit',
            type: 'POST',
            data: data,
            success: function(data) {

                $('#modalEdit').hide('slow');
                loadEmployee();
                alert(data.msg);
            },
            error: function() {

            }
        });
    });

    function success_callback() {
        $('#modalEdit').hide('slow');
        loadEmployee();
        return false;
    }


    function loadEmployee() {
        //alert("hi");
        $.ajax({
            url: '/Application/Employee/Index',

            success: function (data) {
                //alert(data);
                $('#output').html(data);
            }
        });

    }
</script>