Hello I want to Pass value to method defined in controller in AngularJS from Webview Controller android. I am sending my code please check. Thanks in Advance.
myBrowser = (WebView) findViewById(R.id.mybrowser);
client = new WebChromeClient();
final MyWebClient myJavaScriptInterface = new MyWebClient(this);
myBrowser.addJavascriptInterface(myJavaScriptInterface, "AndroidFunction");
myBrowser.setWebChromeClient(client);
myBrowser.getSettings().setJavaScriptEnabled(true);
myBrowser.loadUrl("file:///android_asset/angularjsandroid.html");
myBrowser.loadUrl("javascript:callFromActivity1(\'" + json+ "\')");
JS code
function personDetail($scope) {
$scope.getPersonDetail = function() {
var jsonString = JSON.stringify($scope.data);
showAlert(jsonString);
};
$scope.updatePersonDetail = function(details){
AndroidFunction.getJSONData($scope.id);
};
$scope.callFromActivity1 = function(msg) {
alert(msg);
};
});
Yes, got it that way indeed :
var angular_scope = angular.element($("#main_content")).scope();
And then you do whatever you want with it
Related
Here is my goal:
I'm trying to display the details of an event in my modal.
For that, I execute a javascript script which returns to the "GetEventsDetails" method of my "Event" controller with the id of the event.
When I debug with Chrome, I see the id pass except that in my controller, the value is always 0.
I do not really understand why, I checked a lot on the net and everything seems right on my side!
Is it because I do not use an ajax call?
Thank you in advance!
function GetEventsDetails(id) {
//$('#myModal').find('.modal-title').text("Details ");
$.get("#Url.Action("GetEventsDetails", "Events")/" + id,
function (data) {
$('.modal-body').html(data);
})
$('#myModal').show();
}
</script>
}
[Authorize]
[HttpGet]
public async Task<ActionResult> GetEventsDetails(int Zkp)
{
ViewBag.sessionv = HttpContext.Session.GetInt32("idMember");
FileMakerRestClient client = new FileMakerRestClient(serverName, fileName, userName, password);
var toFind = new Models.EventsLines { Zkp = Zkp };
var results = await client.FindAsync(toFind);
bool isEmpty = !results.Any();
if (isEmpty)
{
return View();
}
Models.EventsLines oEventViewModel = new Models.EventsLines();
oEventViewModel = results.ToList().First();
Console.WriteLine(oEventViewModel);
return PartialView(oEventViewModel);
}
<script>
function GetEventsDetails(id) {
//$('#myModal').find('.modal-title').text("Details ");
var urlpath = "/ Events / GetEventsDetails /" + id;
$.get(urlpath, function (data) {
$('.modal-body').html(data);
});
$('#myModal').show();
}
</script>
And Your Controller
public async Task<ActionResult> GetEventsDetails(int id)
I am having issues retrieving parameters from my URL that is an API. Any
help would be greatly appreciated.
Here is my c# code
[Route("api/[controller]")]
public class PasswordController : Controller
{
private readonly AppSettings _options;
public PasswordController(IOptions<AppSettings> optionsAccessor)
{
_options = optionsAccessor.Value;
}
[HttpGet]
//this isnt returning anything...
public IActionResult Get([FromQuery]string emp)
{
var x = HttpContext.Request.Query["emp"].ToString();
Response.Headers.Add("x-emp-name", x);
return Json(_options.ClientSettings);
}
Here is my angular code ts
private GetData(): void {
this.http.get('api/password').subscribe(values => {
this.ViewOptions = values.json();
this.titleService.setTitle(this.ViewOptions.changePasswordTitle + " -
" + this.ViewOptions.applicationTitle);
if (this.ViewOptions.recaptcha.isEnabled) {
this.FormGroup.addControl('reCaptcha', new FormControl('',
[Validators.required]));
const sp = document.createElement('script');
sp.type = 'text/javascript';
sp.async = true;
sp.defer = true;
sp.src =
'https://www.google.com/recaptcha/api.js?onload=vcRecaptchaApiLoaded&render=explicit&hl='
+ this.ViewOptions.recaptcha.languageCode;
}
});
}
Here is my browser console screenshot
You can pass a parameter into your method:
private GetData(queryParam): void {
this.http.get('api/password?emp=' + queryParam).subscribe(values => {
this.ViewOptions = values.json();
///code omitted
note: I don't know the exact syntax for TypeScript parameters so this probably isn't copy/paste-able.
So as I understand your question, you try to call the api/password endpoint with the get parameter ?emp=Test from within an angular web app.
As I see you don't call the endpoint with the parameter but call the whole angular app with the parameter. So my suggestion was to call
this.http.get('api/password?emp=Test').subscribe
from the typescript code.
I am trying to to show the Json data from controller to the view. It works fine in my test project, but when I copied the work in the main project it gives error.
It says Url does not exist in the current context. Although it works fine in the test project and doesn't give this error.
Controller Code -
public JsonResult GetFreight()
{
string url = "https://digitalapi.auspost.com.au/postage/parcel/domestic/calculate.json?length=22&to_postcode=3000&from_postcode=2000&weight=1.5&height=7.7&width=16&service_code=AUS_PARCEL_REGULAR";
//synchronous client.
var client = new WebClient();
client.Headers.Add("auth-key:a1234567-abcd-abcd-1234-1234567890abc");
var content = client.DownloadString(url);
var serializer = new JavaScriptSerializer();
var jsonContent = serializer.Deserialize<Object>(content);
return Json(jsonContent, JsonRequestBehavior.AllowGet);
}
View Code
<script>
var weather = Object();
$(document).ready(function () {
$.get("#Url.Action("GetFreight", "ShoppingCart")", function (response) {
//response
console.log(response);
weather = ko.mapping.fromJS(response); //populate the weather object
ko.applyBindings(weather);
});
});
</script>
<td>Freight = <span data-bind="text:postage_result.total_cost"></span></td>
I want to mention one more thing- In the main project the view is placed in another subfolder called "ShoppingCart" so do I need to change anything in the script when calling the method from the controller? Any help will be appreciated.
Thanks.
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 };
}
I have two click methods in my javascript as follows. Method 1 is hitting the controller method but after that when clicking on a button for Method 2, it is not hitting the controller. Here I dont want to use $.ajax call for submit. I tried different ways but am not sure why method 2 is not hitting the controller. Appreciate any inputs. Thanks.
Method 1:
$("#selectAll").click(function () {
var familyDetailsForm = $("#family_details");
var enrollmentSetupId = $("#enrollmentSetupId").val();
var eId = $("#eId").val();
var url = "";
if($("#isDental").val() == "true"){
url = GlobalVars["app_url"] + "/shop/search/addAllDentalPlans?enrollmentSetupId=" +
enrollmentSetupId+"&eId="+eId;
}
else {
url = GlobalVars["app_url"] + "/shop/search/addAllHealthPlans?enrollmentSetupId=" +
enrollmentSetupId+"&eId="+eId;
}
familyDetailsForm.attr("action", url);
familyDetailsForm.submit();
});
Method 2:
$("#removeAll").click(function () {
var remove_familyDetailsForm = $("#family_details");
var remove_enrollmentSetupId = $("#enrollmentSetupId").val();
var planType = $("#planKind").val();
var url = "";
if($("#isDental").val() == "true"){
url = GlobalVars["app_url"] + "/shop/search/removeAllDentalPlans?
remove_enrollmentSetupId=" +remove_enrollmentSetupId+"&planType="+planType;
}
else {
url = GlobalVars["app_url"] + "/shop/search/removeAllHealthPlans?
remove_enrollmentSetupId=" +remove_enrollmentSetupId+"&planType="+planType;
}
remove_familyDetailsForm.attr("action", url);
remove_familyDetailsForm.submit();
});
Controller:
#RequestMapping(value = "removeAllHealthPlans", method = RequestMethod.POST)
public String removeAllHealthPlans(HttpSession session, HttpServletRequest request, Model model)
throws Exception {
First check if your method is properly mapped. It should be rather
#RequestMapping(value = "/removeAllHealthPlans", ...)
This is of course assuming that your controller is mapped as /shop/search