Handling MVC action result using JQuery post method - asp.net-mvc-3

I am calling MVC action something like below:
var RestaurantDetailsUIforForeignWidget = {
frmId: '',
onFormSubmit: function () {
var frm = $(RestaurantDetailsUIforForeignWidget.frmId);
var divResult;
$('.offerbox').hide();
$.post(frm.attr('action'), frm.serialize(), function (html) {
// $('#section-time-slots').html(html)
$('#contentAll').html(html);
DisplayOffer();
});
return false;
},
updateTimeDesc: function () {
$('#time').val($('#SittingTime option:selected').html());
},
init: function (frmId) {
RestaurantDetailsUIforForeignWidget.frmId = frmId;
$('#SittingTime').bind('change', RestaurantDetailsUIforForeignWidget.updateTimeDesc);
$(frmId).bind('submit', RestaurantDetailsUIforForeignWidget.onFormSubmit);
RestaurantDetailsUIforForeignWidget.updateTimeDesc();
}
};
As you can see $('#contentAll').html(html); updates whole view content with the result. What I want is to get a single div from html output and update the $('#section-time-slots') instead.
Please help me guys... thanks :)

Try this:
$.post(frm.attr('action'), frm.serialize(), function (html) {
$('#section-time-slots').html($("#IdOfRequiredElementInResponse", html).html());
DisplayOffer();
});

Related

Pass DataTable reference to the callback function on load

My current code is:
var CommissionLogs = $("#CommissionLogs").DataTable({
ajax: {
url: ajaxurl + '?action=pos&post_action=get_commissions'
},
'initComplete': function (settings, json){
//possible to access 'this'
this.api().columns(1);
}
});
I improved the code above as below with help :
var CommissionLogs = $("#CommissionLogs").DataTable({
ajax: {
url: ajaxurl + '?action=pos&post_action=get_commissions'
},
'initComplete': function(settings, json){
callbackFunction(settings);
}
});
function callbackFunction(settings){
var api = new $.fn.dataTable.Api( settings );
// api is accessible here.
}
Update :
Now I can access api from callback function. But I want use same callback with load() as below code.
CommissionLogs.ajax.url( newAjaxURL ).load( callbackFunction(), true);
But settings param is not accessible in load function.
I can clear and destroy datatable and re initialize always. But what will be the right way.
I think you need settings:
https://datatables.net/reference/type/DataTables.Settings
$('#example').dataTable( {
"initComplete": function(settings, json) {
myFunction(settings);
}
});
function myFunction(settings){
var api = new $.fn.dataTable.Api( settings );
// Output the data for the visible rows to the browser's console
// You might do something more useful with it!
console.log( api.rows( {page:'current'} ).data() );
}
Other option is re-use your var CommissionLogs variable throughout the code without using this, I recommend strongly this last option.
The dataTable.ajax.url().load() has not access to settings.
So can not call a callback function with settings.
But possible to use callback function without settings.
So here is an alternative way to use settings.
CommissionLogs.clear();// clear the table
CommissionLogs.destroy();// destroy the table
CommissionLogs = $("#CommissionLogs").DataTable({
ajax: {
url: newAjaxUrl
},
'initComplete': function (settings, json){
callbackDatatableFunciton(settings);
}
});

How to refresh content when using CrossroadJS and HasherJS with KnockoutJS

I was following Lazy Blogger for getting started with routing in knockoutJS using crossroads and hasher and it worked correctly.
Now I needed to refresh the content using ajax for Home and Settings page every time they are clicked. So I googled but could not find some useful resources. Only these two links
Stack Overflow Here I could not understand where to place the ignoreState property and tried these. But could not make it work.
define(["jquery", "knockout", "crossroads", "hasher"], function ($, ko, crossroads, hasher) {
return new Router({
routes:
[
{ url: '', params: { page: 'product' } },
{ url: 'log', params: { page: 'log' } }
]
});
function Router(config) {
var currentRoute = this.currentRoute = ko.observable({});
ko.utils.arrayForEach(config.routes, function (route) {
crossroads.addRoute(route.url, function (requestParams) {
currentRoute(ko.utils.extend(requestParams, route.params));
});
});
activateCrossroads();
}
function activateCrossroads() {
function parseHash(newHash, oldHash) {
//crossroads.ignoreState = true; First try
crossroads.parse(newHash);
}
crossroads.normalizeFn = crossroads.NORM_AS_OBJECT;
hasher.initialized.add(parseHash);
hasher.changed.add(parseHash);
hasher.init();
$('a').on('click', function (e) {
crossroads.ignoreState = true; //Second try
});
}
});
Crossroads Official Page Here too I could not find where this property need to be set.
If you know then please point me to some url where I can get more details about this.

Kendo grid how to pass additional parameter from java script

in telerik extenstion to pass additional data to ajax request I used
function onDataBinding(e)
{
e.data = {argument : 4};
}
where e was div cointainer with data object inside,
How can I do this using kendo ? I tried the same but for Kendo e arqument is sth totally different.
Finally i got the answer my own and it is :
$('#grid').data('kendoGrid').dataSource.read({name:value})
Sorry for the terrible late at the party, but i've got some special cake that you may find tasty:
function readData()
{
return {
anagId: selectedItem.ID
};
}
$("#grid").kendoGrid({
dataSource: {
type: "ajax",
transport: {
read: {"url":"#Url.Action("RecordRead", "Tools")","data":readData}
}
[ rest of the grid configuration]
I came across this code by inspecting the code generated by Kendo Asp.Net MVC helpers.
I don't know if this is a further implementation that didn't exist at the age of the post, but this way looks really the most flexible compared to the other answers that i saw. HTH
Try this:
Add this to your grid read function or any CRUD operation:
.Read(read => read.Action("ReadCompanyService", "Admin").Data("CompanyServiceFilter"))
Add javascript:
function CompanyServiceFilter()
{
return {
company: $("#ServiceCompany").val()
}
}
In your controller:
public ActionResult ReadCompanyService([DataSourceRequest]DataSourceRequest request, string company)
{
var gridList = repository.GetCompanyServiceRateList(company);
return Json(gridList.ToDataSourceResult(request));
}
Please note, only string type data is allowed to be passed on read, create, update and delete operations.
If you want to pass some param to ajax request, you can use parameterMap configuration on your grid.
This will get passed on to your Ajax request.
parameterMap: function (options, operation) {
if (operation === "read") {
var selectedID = $("#SomeElement").val();
return {ID: selectedID }
}
return kendo.stringify(options.models) ;
}
Try this:
.Read(read => read.Action("Controller", "Action")
.Data(#<text>
function() {
return {
searchModel: DataFunctionName(),
userName: '#=UserName#'
}
}
</text>)
)
JS function
function DataFunctionName() {
var searchModel = {
Active: $("#activityMonitorIsActive").data('kendoDropDownList').value(),
Login: $("#activityMonitorUsers").data('kendoComboBox').value()
};
return searchModel;
}

Load JavaScript when partial is called via ColorBox?

It seems when loading a Razor partial view via ColorBox (not using an iframe), the JavaScript libraries do not initialize properly or it is an artifacte of the partial. If I include the libraries in the parent page, the JavaScript function runs inside the partial jsut fine. I don't see any errors coming from the browser when the library is in the partial, but it is not working. If I move the library (in this case fileuploader.js) outside of the partial and keep the function in the partial it works fine.
Example:
<script src="#Url.ContentArea("~/Scripts/plugins/ajaxUpload/fileuploader.js")" type="text/javascript"></script>
<div id="file-uploader">
<noscript>
<p>
Please enable JavaScript to use file uploader.</p>
</noscript>
</div>
<script>
$(function () {
var fileCount = 0;
var uploader = new qq.FileUploader({
element: document.getElementById('file-uploader'),
action: '/Admin/Avatar/AvatarUpload',
debug: true,
params: {
'userId': '#ViewBag.UserId'
},
onSubmit: function (id, fileName) {
fileCount++;
},
onComplete: function (id, fileName, responseJson) {
if (responseJson.success) {
if (createAvatar(responseJson.file, responseJson.imageId)) {
fileCount--;
} else {
fileCount--;
}
} else {
$("span.qq-upload-file:contains(" + fileName + ")").text(responseJson.errorMessage);
fileCount--;
}
if (fileCount == 0) {
.....
}
},
onCancel: function (id, fileName) {
fileCount--;
if (fileCount == 0) {
....
}
}
});
});
<script>
You may want to check whether there are duplicate references to the JavaScript libraries you are using (one in the parent and one in the partial).
This is a common issue and it will not raise any errors whatsoever, but will stop your JavaScript code from executing.
I think this is a time line problem.Before the "Partial View" load(or appending the div) JavaScript try to bind it and fail.So it cannot find a element which is in your Partial View document.I had a problem with like this with "ColorBox".I have found a solution for this problem.For example : When you call GET or POST method ,after the query put a control point like this .For example for binding "colorbox" :
function getMyPartial(partialname) {
var resultDiv = document.getElementById("content");
$.ajax({
type: "GET",
url: partialname,
async: false,
success: function (data) {
resultDiv.innerHTML = "";
resultDiv.innerHTML = data.toString();
}
});
var indd = 0; //This is Control Point
if (partialname == "YourPartialName") {
var yourelementinpartial= document.getElementById("example");
while (!yourelementinpartial) {
indd++;
}
$(".group4").colorbox({ rel: 'group4' }); //binding point
}
}
At the control point, if any of the element in your PartialView document has found it will bind.

how to pass a parameter to actionlink from a script

I have a script:
function FindSerial() {
var textBoxValue = $("#clientSerial1").val();
return textBoxValue;
};
My actionlink is :
#Html.ActionLink("talks", "ClientTalks", "Talk", new { id ="FindSerial()" }, null)
I want to use the function in order to get id ; how can it be done?
#Jalai Amini is right. You will need to handle it with jquery. Something like this:
#Html.ActionLink("talks", "ClientTalks", "Talk", new { id="talklink"})
<script>
$(function () {
$('#talklink').click(function () {
document.location.href = $(this).attr("href") + "?id=" + FindSerial();
}
});
</script>
Something to consider:
In this way you are creating the url in the client side, so it can't use the mvc routes. In my example, it will be putting the id as a querystring parameter, but it could be another thing.

Resources