how to pass params in remotefunction - javascript

I have a javascript function with remotefunction,,, in that remotefunction i want to pass map has parameter and i want to use that map variable in controller action,, i don't know how to pass that in params of ramotefunction and to use it in that particular controller action...
jQuery(document).ready(function(){
alert("checking for checkbox");
var countryId = document.getElementById("countryId").value;
jQuery('#groupdelete').on('click', function(){
var names = {};
alert("*********");
jQuery('input:checked').each(function() {
alert(jQuery(this).attr("id"));
if(jQuery(this).attr("id")) {
var id=jQuery(this).attr("id")
var costId = "c"+id
var ntb = document.getElementById(costId).value;
alert(ntb);
names[id] = ntb;
}
});
alert(names[1]);
})
${remoteFunction(action:'addLabServiceToCountry', controller:'country', params:'\'names=\'+names')}
})
params:'\'names=\'+names' which is not working properly, how to pass map variable in params of remotefunction and in contoller action how to access that.

Try this:
${remoteFunction({action: "addLabServiceToCountry", controller: "country", params: names});
Then in remoteFunction() you need to iterate through params to get all mapped names.
Or you can convert names to a string:
var namesStr = names.join(',');
and then pass the string:
${remoteFunction({... , params: namesStr});

Related

Use JavaScript variable as route argument

I try to add $(this).prev("input").val() in my id argument for an API route, but I don't know how to stop the C# part , I thought about <text></text> or #: but doesn't work like this.
Anyone has a trick ? (thought about writting the URL instead of using the RouteURL function but I don't think it's a good way to program)
$.ajax({
url: '#Url.RouteUrl("IsTranslated", new { id = <text>$(this).prev("input").val()</text> }, new {market=#ViewBag.market })
// [...]
})
You can't inject a JavaScript value like that (remember, the Razor code is evaluated server-side). What you can do is use your helper to build a "template" string, and replace the id value:
var template = '#Url.RouteUrl("IsTranslated", new { id = 0 }, new { market=#ViewBag.market })';
var id = $(this).prev("input").val();
var url = template.replace('id=0', 'id='+id);
$.ajax({
url: url
// [...]
})
This assumes, of course, that a querystring value is generated by the helper. If not, this might work:
var template = '#Url.RouteUrl("IsTranslated", new {}, new { market=#ViewBag.market })';
var id = $(this).prev("input").val();
var url = template.replace('IsTranslated', 'IsTranslated?id='+id);
$.ajax({
url: url
// [...]
})

Pasing Javascript result to View

I got a Question, I'm really new in working with Asp.net.
I got a Javascript where I woult like to pass Data to my Controller.
<script type="text/javascript">
$("#SearchButton").on("click", function () {
var $sucheMoped = [];
$("#tab_logic tbody tr")
.each(function () {
var $Item = $(this);
var suchfeld = $Item.find("td > input[name='Suchfeld']").val();
var schluessel = $Item.find("td > select[name='Suchschluessel'] > option:selected").val();
alert(suchfeld + "&&&" + schluessel);
$sucheMoped.push({
Suchfeld: suchfeld,
Suchschluesseltyp: schluessel
});
});
window.open('#Url.Action("MainView","MainView")?SuchObject='+$sucheMoped);
})
</script>
I just would like to pass the "sucheMoped" from my javaScript to my Controller.
My Controller is just expecting a IEnumarable of Objects with Properties Suchfeld and Suchschluesseltyp.
Anyone an idea?
Thanks Guys.
First of all, you need to change the way you invoke the controller action. You should stringify the array using the JSON.stringify() method.
So, this should look like this:
window.open('#Url.Action("MainView","MainView")?SuchObject='+JSON.stringify($sucheMoped));
Then, you need to create a custom model binder to bind your array with the action parameter. This is a simple array model binder for demonstration purposes only, it doesn't take into account failures or whatever, but it works in this scenario, passing the correct data, so please modify it to fit your needs.
public class ArrayModelBinder: DefaultModelBinder
{
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var rawArray = controllerContext.HttpContext.Request.QueryString["SuchObject"];
var array = JsonConvert.DeserializeObject<IEnumerable<MyObject>>(rawArray);
return array;
}
}
What I do here, is to get the query string submitted through the URL, convert it with JsonConvert.Deserialize<T> method and return it.
You simply need to decorate your parameter in the controller's action with the custom model binder, like this:
[HttpGet]
public ActionResult Search([ModelBinder(typeof(ArrayModelBinder))]IEnumerable<MyObject> SuchObject)
{
return View(SuchObject);
}
Edit
window.open is useful if you want to open a new browser window. You could use it to open a new tab as well.
In order to navigate to another location without opening a new tab or window, use the window.location property like the following:
window.location = '#Url.Action("Search", "Home")?SuchObject=' + JSON.stringify(array);
If you use the jQuery.ajax method, you can pass complex objects as data parameter.
$.ajax({
url: '#Url.Action("MainView", "MainView")',
type: 'GET',
data: { 'SuchObject': $sucheMoped },
success: function (htmlContent) {
// write content to new window (from http://stackoverflow.com/a/23379892/1450855)
var w = window.open('about:blank', 'windowname');
w.document.write(htmlContent);
w.document.close();
}
});
You can use jquery library $.getScript to call the action method in your controller and the return javascriptResult type in your action.
$.getScript("Home","Display")
// Home Controller
private JavaScriptResult Display()
{
string message = "alert('Hello World');";
return new JavaScriptResult { Script = message };
}

How to access $scope object in factory using AngularJS?

I have serialize method for post , So riskAssessmentKey is not part of $scope.topRiskDTO but i pass the riskAssessmentKey value from $scope.riskAssessmentDTO.riskAssessmentkey and now i am posting to factory but when i save all values are posting but riskAssessmentKey is coming undefined i dont know why..
So far tried code....
parentCtrl.js
$scope.addTopRisk = function(){
topRiskGridConfig.topRiskmodalWinConfig.title = 'Add top Risk';
$scope.viewTopRiskWin.setOptions(topRiskGridConfig.topRiskmodalWinConfig);
$scope.$broadcast('addTopRisk',$scope.riskAssessmentDTO.riskAssessmentKey);
};
childCtrl.js
$scope.topRiskDTO = {};
$scope.issuePltDataSource = kendoCustomDataSource.getDropDownDataSource('RA_KY_CNCRN_IS_PLTFM');
$scope.$on('addTopRisk', function (s,id){
$scope.riskAssessmentDTO.riskAssessmentKey = id;
$scope.viewTopRiskWin.open().center();
$scope.submit = function(){
rcsaAssessmentFactory.saveTopRisk($scope.topRiskDTO,id).then(function(){
$scope.viewTopRiskWin.close();
});
};
});
factory.js
var serializeTopRisk = function (topRisk,id) {
var riskAssessmentKey = id;
var objToReturn = {
topRiskName: topRisk.topRiskName,
mitigationActivityDes: topRisk.mitigationActivityDes,
issuePltfLookUpCode: topRisk.issuePltfLookUpCode,
issueNo: topRisk.issueNo,
riskAssessmentKey: topRisk.riskAssessmentKey
};
if(topRisk.riskAssessmentKey){
objToReturn.riskAssessmentKey = topRisk.riskAssessmentKey;
}
return objToReturn;
};
saveTopRisk: function(topRisk,id) {
var request = serializeTopRisk(topRisk);
console.log('request payload', JSON.stringify(request));
console.log('ID :: ', id);
var endpoint = 'app/assessment/rest/addTopRisks';
return $http.post(endpoint, request);
}
You forgot to pass the id to the serializeTopRisk function.
So you already pass the params correctly this this:
saveTopRisk: function(topRisk,id) {
var request = serializeTopRisk(topRisk);
But then serializeTopRisk should also get the id
var serializeTopRisk = function (topRisk, id) { // added the id over what you originally had
var riskAssessmentKey = $rootScope.riskAssessmentDTO.riskAssessmentKey; // drop this, use id instead
Don't use rootScope to pass data between the factory and the controller if you don't need to (it looks like you are already passing values to the factory from the controller by supplying it with object inputs, keep it that way and drop the rootScope usage from the factory).

Navigate using router and pass an object as a query string

I have two modules that I want to connect by navigating from one to the other. Since there are going several parameters to be passed, I want to use query string. Is there a way to use the built-in router to navigate to a module and have my object arguments being passed like
var params = {
param1: "parameter",
param2: "anotherparameter"
}
router.navigate("theothermodule", params);
or do I have to manually parametrize the object into the url string and pass it to router.navigate like
router.navigate("theothermodule?" + $.param(params));
Another solution would be :
var params = {
param1: "parameter",
param2: "anotherparameter"
}
//notes : this object can contain arrays like knockout observable()
//or observableArray();
1.- create the object (params) in shell.js and map it to your route definition like
bellow :
{ route: 'routestr/:id', moduleId: 'viewmodels/adir/mymodul', title: 'je suis',
hash: '#routestr', nav:3, routobj: params }
2.- you could update, even add new members to your object from anywhere before calling this route, by hacking the object from the route.
var myrouteconfig = router.activeInstruction().config;
myrouteconfig.param2 = newvalue;
myrouteconfig.newdlyParam = value;
router.navigate("#routestr/" + id);
3.- Then, in the receipt module :
var activate = function (id) {
//var myid = parseInt(id); //noelem rubriq
var myrouteconfig = router.activeInstruction().config;
var mycallobject = myrouteconfig.params; //your object params
var valparam2 = mycallobject.param2; // your param2 last value
......
}
You have to manually parametrize the object into the url string and map in router.activate (http://durandaljs.com/documentation/Using-The-Router/).
However you can share data with Events(http://durandaljs.com/documentation/Leveraging-Publish-Subscribe/) or Activation Data property in Composition binding(http://durandaljs.com/documentation/Using-Composition/).

Passing a JavaScript variable to a helper method

I am using ASP.NET MVC 3 and the YUI library.
I created my own helper method to redirect to an edit view by passing in the item's ID from the Model as such:
window.location = '#Url.RouteUrl(Url.NewsEdit(#Model.NewsId))';
Now I am busy populating my YUI data table and would like to call my helper method like above, not sure if it is possible because I get the item's ID by JavaScript like:
var formatActionLinks = function (oCell, oRecord, oColumn, oData) {
var newsId = oRecord.getData('NewsId');
oCell.innerHTML = 'Edit';
};
Store your URL with some custom ID, which you'll now to replace later on:
var myurl = '#Url.RouteUrl(Url.NewsEdit(0))'; //Let's use zero
later on:
var formatActionLinks = function (oCell, oRecord, oColumn, oData) {
var newsId = oRecord.getData('NewsId');
//lets use the url we defined above, and replace the zero with our id.
oCell.innerHTML = 'Edit';
};

Categories

Resources