从JS对话框中单击发布到Controller操作方法

时间:2012-12-12 19:03:09

标签: jquery asp.net-mvc razor

我的视图中有一个JS对话框。返回视图时,对话框最大化/打开。该视图还有一个链接,当用户单击链接时,此对话框将打开。

我在对话框中有一个名为Submit的按钮。我想要做的是当模态框打开时,页面元素的其余部分应该模糊或去掉。当他们单击对话框中的提交按钮时,它应该将模型属性发布到控制器操作方法。我不是很擅长JS语法但是如何在提交点击中回复到名为“Create”的控制器操作,提交值为“确认”?

@model RunLog.Domain.Entities.RunLogEntry
@{
    ViewBag.Title = "Create";
    Layout = "~/Views/Shared/_Layout.cshtml";

}

@using (Html.BeginForm("Create", "RunLogEntry", FormMethod.Post, new { id = "form", enctype = "multipart/form-data" }))
    {
        @Html.ValidationSummary(true)
        <div class="exception">@(ViewBag.ErrorMessage)</div>

        //xyz elements here

            <div class="bodyContent">
        <span class="leftContent">
            @Html.Label("Run Dates")
        </span><span class="rightContent"><span id="RunDatesChildDialogLink" class="treeViewLink">
            Click here to Select Run Dates</span>
            <br />
            <span id="RunDatesDisplayy"></span></span>
    </div>

    <div id="runDatestreeview" title="Dialog Title" style="font-size: 10px; font-weight: normal;
        overflow: scroll; width: 800px; height: 450px; display: none;">
        <table class="grid" style="width: 600px; margin: 3px 3px 3px 3px;">
            <thead>
                <tr>
                    <th>
                        Run Dates:
                    </th>
                </tr>
            </thead>
            <tbody>
                    @Html.EditorFor(x => x.RunDatesDisplay)
            </tbody>
        </table>
    </div>
}

DialogBox的JS文件(runDates.js):

var RunDialog;
$(document).ready(function () {

    RunDialog = $("#runDatestreeview").dialog({ resizable: false, autoopen: false, height: 140, modal: true, width: 630, height: 400,
        buttons: { "Submit": function () {
            $(this).dialog("close");
        },
            Cancel: function () {
                $(this).dialog("close");
            }
        }
    });

    $('#RunDatesChildDialogLink').click(function () {
        RunDialog.dialog('open');
        $("#runDatestreeview").parent().appendTo("form");
    });

    $("#runDatestreeview").parent().appendTo("form");
});

控制器操作:

[HttpPost]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(RunLogEntry runLogEntry, String ServiceRequest, string Hour, string Minute, string AMPM,
                                     string submit, IEnumerable<HttpPostedFileBase> file, String AssayPerformanceIssues1, List<string> Replicates)
        {




**EDIT:**


var RunDialog;

$(document).ready(function () {

    RunDialog = $("#runDatestreeview").dialog({ resizable: false, autoopen: false, height: 140, modal: true, width: 630, height: 400,
        buttons: { "Continue": function () {
            var str = $("#form").serialize();

            $.ajax({
                url: "/RunLogEntry/Create",
                data: str,
                cache: false,
                type: 'POST',
                dataType: 'json',
                contentType: "application/json;charset=utf-8",
                success: function (data, status) {
                },
                error: function (xhr, ajaxOptions, thrownError) { alert('error') }
            });

        },
            Cancel: function () {
                $(this).dialog("close");
            }
        }
    });

    $('#RunDatesChildDialogLink').click(function () {
        RunDialog.dialog('open');
        $("#runDatestreeview").parent().appendTo("form");
    });

    $("#runDatestreeview").parent().appendTo("form");
});

2 个答案:

答案 0 :(得分:1)

示例显示如何将数据发布到控制器方法

剃刀代码:

<div id="form">
        <table width="600">
            <tr>
                <td>Select Date:</td>
                <td>
                    <input class="txtDate" type="date" size="20"></td>
            </tr>
            <tr>
                <td>Select Expense Type:</td>
                <td>
                    <select class="ExpenseType">
                        <optgroup label="Room">
                            <option>Room Fare</option>
                        </optgroup>

                        <optgroup label="Mess">
                            <option>Monthly Mess</option>
                        </optgroup>

                        <optgroup label="Others">
                            <option>Bus Fare</option>
                            <option>Tapari</option>
                            <option>Mobile Recharge</option>
                            <option>Auto</option>
                        </optgroup>
                    </select></td>
            </tr>
            <tr>
                <td>Enter Cost:</td>
                <td>
                    <input  class="cost" type="text" size="45" /></td>
            </tr>
            <tr>
                <td>Extra Details:</td>
                <td>
                    <input class="extra" type="text" size="45" /></td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <button href="javascript:void(0);" onClick="saveExpense();" >Submit</button></td>
            </tr>
        </table>
    </div>

JQuery代码:

   <script>
function saveExpense()
    {
        var expenseobject = {
            date:$('.txtDate').val() ,
            type:$('.ExpenseType').val() ,
            cost: $('.cost').val(),
            extra:$('.extra').val()

        };

        $.ajax({
            url: './saveexpense',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify({ obj: expenseobject }),
            success: function (result) {
                handleData(result);

            }
        });

    }
</script>

<强>控制器:

 public ActionResult SaveExpense(Expense obj)
        {
            obj.ExpenseId = Guid.NewGuid();
            if (ModelState.IsValid)
            {
                context.expenses.Add(obj);
                context.SaveChanges();
                int total=context.expenses.Sum(x => x.cost);
                return Json(new {spent=total,status="Saved" });

            }
            else
                return Json(new { status="Error"});   
        }

希望这会让你度过难关......

答案 1 :(得分:1)

我刚做了一个简单的帖子并使用了form.serialize而不是手动设置每个模型属性。简短

$.post("/RunLogEntry/Create", $("#form").serialize(), function (json) {
            // handle response
        }, "json");