Issue when submitting form data via JQuery UI Dialog to the server - asp.net-mvc

I have an asp.net mvc app, using JQuery UI dialog. I'm trying to submit form data to the controler action method. I do hit the action method but my object has no data. Do you know why?
From Filter.cshtml
$("#selectUnits").dialog({
autoOpen: false,
title: 'Select Units',
width: 400,
modal: true,
minHeight: 200,
buttons: {
"Cancel": function () {
$(this).dialog("close");
},
"Submit": function () {
$.post('/Data/SetUnitNumbers', $("#frmSelectedUnits").submit(), function (data) {
alert('This worked');
});
}
} // END OF BUTTONS
}); //END OF DIALOG
From Controler...Action Method:
public void SetUnitNumbers(object data)
{
int a = 5;
}
From SelectUnits.cshtml where form 'frmSelectedUnits' lives. Essentially it is a bunch of checkboxes values that I'm trying to send back to the server:
<body>
<form id="frmSelectedUnits" action="/" >
<div id="unitNumberCheckboxes" style=" ">
<div>
#Html.CheckBox("SelectAllUnitNumbers", false)<label for="SelectAllUnitNumbers"><b>Select/Unselect All Units</b></label>
</div>
<div id="unitCheckboxes">
#foreach (var item in Model)
{
<div style="float:left">
#Html.CheckBox("UnitNumbers", false)<label for="UnitNumbers">#item.unit_number.ToString().PadLeft(3, '0') </label>
</div>
}
</div>
</div>
</form>
</body>

jQuery .post is:
$.post(url, data, success-callback-function);
where data is A map or string that is sent to the server with the request.
Calling $("#frmSelectedUnits").submit() probably won't work.
Try:
$.post('/Data/SetUnitNumbers', $("#frmSelectedUnits").serialize(), function (data) {
alert('This worked');
});
jQuery docs on .serialize()

Related

slideToggle and jQuery Ajax - New elements inoperable

When I introduce new elements to my slideToggle they look fine and are active (expanded by default) however if I click a pre-existing element all elements collapse and I cannot expand the new ajax elements. Essentially the new ajax elements are not part of the slideToggle group because that was constructed before the elements were introduced. How do I rebuild the toggle on the fly or make the new elements behave as expected?
** jQUERY
$('div.menu_body:eq(0)').show();
$('.acc .head:eq(0)').show().css({color:"#2B6893"});
$(".acc .head").click(function() {
$(this).css({color:"#2B6893"}).next("div.menu_body").slideToggle(300).siblings("div.menu_body").slideUp("slow");
$(this).siblings().css({color:"#404040"});
});
** Ajax
<script type="text/javascript">
jQuery(document).ready(function() {
setInterval("showNewFeeds()", 10000);
});
showNewFeeds() {
$.ajax({
type: 'POST',
url: 'feed.php',
data : {uid : '145', mid: '22', nid: 56'},
success: function(response) {
$('#feedNote').html(response).fadeIn('slow');
},
error: function (xhr, ajaxOptions, thrownError) {
//alert(xhr.status);
//alert(thrownError);
}
});
}
</script>";
** HTML
<div class="widget acc" id="feedNote">
<div class="head"><h5>Header 1</h5></div>
<div class="menu_body">
<div>HTML 1</div>
</div>
<div class="head"><h5>Header 2</h5></div>
<div class="menu_body">
<div>HTML 2</div>
</div>
</div>
Try :
$(document).on('click', '.acc .head', function() {
$(this).css({color:"#2B6893"}).next("div.menu_body").slideToggle(300).siblings("div.menu_body").slideUp("slow");
$(this).siblings().css({color:"#404040"});
});
instead of .click(function(){...})

how to pass Model with Url.Action?

I want to return a partial view in Jquery Dailog and wanted to pass the viewmodel object to particular controller action, how to do that?
View
#Html.DropDownListFor(model => model.SelectedCountry, new SelectList(Model.CountryList, "CountryCode", "CountryName"), "---SELECT COUNTRY---",
new { #class = "chosen", #onchange = "this.form.action='/Home/Index'; this.form.submit(); " })
<input type="button" id="button1" value="Push"/>
<div id="dialog" title="Report" style="overflow: hidden;"></div>
Js
<script type="text/javascript">
$(function () {
$('#dialog').dialog({
autoOpen: false,
width: 400,
resizable: false,
title: 'Report',
modal: true,
open: function() {
//here how to pass viewmodel
$(this).load("#Url.Action("CreatePartial")");
},
buttons: {
"Close": function () {
$(this).dialog("close");
}
}
});
$('#button1').click(function () {
$('#dialog').dialog('open');
});
});
Controller
public ActionResult CreatePartial(HomeViewModel homeViewModel)
{
return PartialView("_CreatePartial", homeViewModel);
}
Currently, "homeViewModel.SelectedCountry" is Null, how to pass model in Jquery?
If you're using AJAX, you should not use HTTP GET to pass model to server. Instead use HTTP POST (as in $().ajax({method: 'POST'}) and pass data as POST data ($().ajax({method: 'POST', data: #Html.Raw(Json.Encode(Model))}))
You convert the model into an JSON object by using the the build-in JSON-helper, just modify your request to:
$(this).load('#Url.Action("CreatePartial")',#Html.Raw(Json.Encode(Model)));
#Html.Raw is needed to prevent HTML-Encoding.
I tested it and it worked.

How I can clear textbox text before ajax form submit event?

I want to clear textbox after ajax posting.
<div style="padding: 5px; background-color: Silver;">
#using (Ajax.BeginForm("_MessagesPartial", "Chat", new AjaxOptions { UpdateTargetId = Model.room_id.ToString() }))
{
<div style="padding: 5px 15px 5px 5px;">
#Html.TextBox("textbox_message", null, new { #class = "text_yorum", id = "text_box_chat" })
#Html.Hidden("oda_id", Model.room_id)
</div>
}
</div>
<div id="#Model.room_id" style="height:400px;overflow-y:scroll;position: relative;">
#Html.Action("_MessagesPartial", "Chat", new { room_id = Model.room_id })
</div>
there are a lot of example, but they do not work. I m already using this code, but it is too slow.
$("form").submit(function () {
$.get('#Url.Action("_MessagesPartial", "Chat", new { room_id = Model.room_id }) ', {}, function (view) {
$("##Model.room_id").html(view);
$("#text_box_chat").val("");
});
});
Is there any way to do this.
I usually use the Ajax function. But anyways I believe the key to your problem is that you have no success function. Try something like this.
$.ajax({
url: 'yourfile.php',
type: 'POST',
success: function() {
$('#myform input').val("");
}
});
You seem to be sending 2 AJAX requests. One sent by the Ajax.BeginForm helper and one inside your custom .submit handler. You could specify a callback which will be executed after the AJAX request completes in the AjaxOptions:
#using (Ajax.BeginForm("_MessagesPartial", "Chat", new AjaxOptions { UpdateTargetId = Model.room_id.ToString(), OnSuccess = "onSuccess" }))
{
...
}
and clear the input inside this callback:
function onSuccess() {
$("#text_box_chat").val("");
}
You don't need to subscribe to the .submit event of the form as you did and send an AJAX request. That's what the Ajax.BeginForm helper already does.

My code doesn't work in Partial View(ascx)?

my code is:
<script type="text/javascript">
$(document).ready(function () {
alert("dd");
//Attach cascading behavior to the orderID select element.
$("#orderID").CascadingDropDown("#customerID", '/Home/AsyncOrders',
{
promptText: '-- Pick an Order--',
onLoading: function () {
$(this).css("background-color", "#ff3");
},
onLoaded: function () {
$(this).animate({ backgroundColor: '#ffffff' }, 300);
}
});
//Attach cascading behavior to the orderDetails select element.
$("#orderDetails").CascadingDropDown("#orderID", '/Sales/AsyncOrderDetails',
{
promptText: '-- Pick an Order Detail --',
onLoading: function () {
$(this).css("background-color", "#ff3");
},
onLoaded: function () {
$(this).animate({ backgroundColor: '#ffffff' }, 300);
}
});
//When an order detail is selected, fetch the details using ajax
//and display inside a div tag.
$('#orderDetails').change(function () {
if ($(this).val() != '') {
$.post('/Sales/OrderDetails', $(this).serialize(), function (data) {
$('#orderDetailsContainer').html(data).effect("highlight", {}, 3000);
});
}
});
});
</script>
<div id="searchFilter">
Custom text in select lists, lists highlight when loading.<br />
<%:Html.DropDownList("customerID", Model, "-- Select Customer --")%>
<%-- <%:Html.DropDownList("cites", ViewData["xml"] as SelectList , "-- Select Customer --")%>--%>
<select id="orderID" name="orderID">
</select>
<select id="orderDetails" name="orderDetails">
</select>
</div>
<div id="orderDetailsContainer">
</div>
and when write it in page(aspx) very god run
but when use Partial View (ascx) do not run code ?
Make sure you do it either like this
<% Html.RenderPartial("YourUserControl"); %>
or (note the colon (:) )
<%: Html.Partial("YourUserControl"); %>
Or your partial view will not be written to the document

Presenting a second form with Jquery UI Dialog and KnockoutJS

I have a primary form defined and nicely laid out, it does what it needs to do...
#{ Html.BeginForm(); }
#Html.ValidationSummary(false)
#Html.AntiForgeryToken()
#Html.EditorFor(model => model)
<h2>Properties</h2>
<hr />
#* I want to put some stuff here... *#
<br class="space" />
<div class="clearfix">>
<button type="submit" data-bind="click: save">
Save
</button>
</div>
#{ Html.EndForm(); }
Now, then. This model (or ViewModel, rather) has an IList<PropertyViewModel> attached to it.
A PropertyViewModel has its own set of validations. They are pretty simple for now, but there is a chance that later there will be more complicated uses for this setup.
I am using KnockoutJS for my viewModel consistency. Though I suppose it is fairly irrelevent. I want to display a second form in a jQuery UI Dialog and return the result, essentially..
<script type="text/javascript">
var viewModel = {
name: ko.observable(),
description: ko.observable(),
properties: ko.observableArray(),
save: function () {
alert(ko.toJSON(viewModel));
},
includeProperty: function () {
$("#dialog").dialog({
width: 500,
closeText: '',
resizable: true,
buttons: {
'Submit': function () {
$(this).dialog('close');
callback( #* I want the new data to get sent back *# );
},
'Cancel': function () {
$(this).dialog('close');
return false;
}
}
});
}
};
function callback(value) {
alert(ko.toJSON(value)); // (I will push the new property to the viewmodel here)
}
ko.applyBindings(viewModel);
</script>
However, I am not really sure how to actually put the EditorTemplate into the dialog, moreover I am not sure how to get the data back out of it.
I don't completely understand your question, but from what I understood what you are trying to do is pass data to the dialog and retrieve data from the dialog. If that is the case then this may be useful:
http://api.jquery.com/jQuery.data/
Here is detailed example on how to use:
Passing data to a jQuery UI Dialog

Resources