0

I have a JS Dialog Box within my view. When the view is returned the dialog box is maximized/open. The view also has a link and when users click on the link this dialog box opens.

I have a button within the dialog called Submit. What I am trying to do is when the modal box is open, the rest of the page elements should be blurred or disbaled. When they click on the submit button within the dialog box, it should post with the Model properties to a controller action method. I am not really good at JS syntax but how would I post back to the controller action called "Create" with a submit value of "Confirmation" within submit click?

@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>
}

JS File For DialogBox(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");
});

Controller Action:

[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");
});
7
  • No, it won,t be submitted because you are just declaring the objects abd not assigning the values to them...Again, url: '@Url.Action("Create", "RunLogEntry")', is wrong Commented Dec 12, 2012 at 20:15
  • It should be url:'./create' Commented Dec 12, 2012 at 20:18
  • well thats what im struggling at. The model is called RunLogEntry which has different properties in the view. I want to submit that. How do i declare var datatosend = model? Commented Dec 12, 2012 at 20:19
  • You are missing "data" in the $.ajax call so how can you post anything? Commented Dec 12, 2012 at 20:20
  • Wait, i will just put that kind of stuff in my answer.. Commented Dec 12, 2012 at 20:21

2 Answers 2

1

Sample To show How you can Post Data to the controller Method

Razor Code:

<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 Code:

   <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>

Controller:

 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"});   
        }

Hope this will get you through now...

Sign up to request clarification or add additional context in comments.

7 Comments

hi bushan, I have another submit button on the page itself. They all submit to the same action. I updated with Controller Action which takes different fields within the form.
So what is the problem now?
Do I need to include a new param of object in my action?
@TjStaton: You have different buttons on the same page sending different data to the same action..Am I getting it right? If yes, then, you will have to call code given in my answer for every button click but you will have to change the datatoSend each time according to your needs..Hope you got the solution now?
I get the solution, I want to pass the entire model back to the controller from this button click in js dialog. So here I will pass the model data: JSON.stringify(obj:dataToSend)?
|
1

I just did a simple post and used form.serialize rather than manually setting every model property. Short and simple

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

1 Comment

@Bushan, Thanks for guiding me in the approach

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.