I am trying to open new window using window.open(actionUrl)
the actionUrl is compose form the action address and url as parameter.
so eventually the actionUrl is :
"/Default/Details?url=http://www.someaddress.com?a1=1&a2=2&a3=3"
However in the action the url i get is :
"http://www.someaddress.com?a1=1"
I do not get "&a2=2&a3=3" parameters
Here is the relevant view code:
<div>
<input type="button" value="test" id="btnTest" />
</div>
<script>
var vurl = '#Url.Action("Details", "Default")';
$(function () {
$("#btnTest").click(function () {
var url = "http://www.someaddress.com?a1=1&a2=2&a3=3";
vurl = vurl + url;
window.open(vurl);
});
})
</script>
and this is the controller and action
public class DefaultController : Controller
{
// GET: Default
public ActionResult Index()
{
return View();
}
// GET: Default/Details/5
public ActionResult Details(string url)
{
return View();
}
}
You need to use the encodeURIComponent function on the url parameter's value:
var actionUrl = '/Default/Details?url=' + encodeURIComponent('http://www.someaddress.com?a1=1&a2=2&a3=3');
The &a2=2&a3=3 part was actually part of the /Default/Details URL, not the http://www.someaddress.com one. Now that the inner URL is URI encoded, it should work.
Make sure to decode the value when using the url parameter though, using decodeURIComponent:
var urlMatch = location.search.match(/url=(.*)&?/);
if (urlMatch) {
var decodedUrl = decodeURIComponent(urlMatch[1]);
// do something with the decoded URL...
}
EDIT
For the first part (URI encoding) and based on your code, you should use it this way:
<div>
<input type="button" value="test" id="btnTest" />
</div>
<script>
var vurl = '#Url.Action("Details", "Default")';
$(function () {
$("#btnTest").click(function () {
var url = "http://www.someaddress.com?a1=1&a2=2&a3=3";
vurl = vurl + encodeURIComponent(url);
window.open(vurl);
});
})
</script>
As for the ASP.NET part and the use of the string url parameter, I'd suggest checking the following post: using decodeURIComponent within asp.net as I'm not familiar with this environment.
Related
I use an AJAX call to a method that returns JSON. How can I read the returned JSON without being redirected to a new empty page?
[HttpPost]
public JsonResult Test()
{
return Json("JSON return test", JsonRequestBehavior.AllowGet);
}
#model List<POC.Web.Intranet.Models.AttachmentPropertyViewModel>
<div>
#using (Ajax.BeginForm("Test", "DMS", new AjaxOptions { HttpMethod = "POST", OnSuccess = "endMethod()", OnBegin = "beginMethod()" }))
{
<h6>Properties</h6>
for (int i = 0; i < Model.Count; i++)
{
#Html.HiddenFor(item => item[i].AttachmentPropertyId);
#Html.HiddenFor(item => item[i].AttachmentMetaDataId);
<label>#Model[i].AttachmentPropertyName</label>
#Html.TextBoxFor(item => item[i].AttachmentPropertyValue, htmlAttributes: new { #class = "form-control property-value-txtbox" });
<br />
}
<input type="submit" id="btnSaveChanges" value="Save Chnages" />
}
<hr />
</div>
<script>
function beginMethod() {
alert("Start");
}
function endMethod() {
alert("Finish");
// also here i want to read the incoming json
}
</script>
First of all , you do not need JsonRequestBehavior.AllowGet because you do a POST request.
[HttpPost]
public JsonResult Test()
{
return Json("JSON return test");
}
Then, change this:
OnSuccess = "endMethod()", OnBegin = "beginMethod()"
To
OnSuccess = "endMethod", OnBegin = "beginMethod"
And in your script, pass response parameter to get json result from controller.
function endMethod(response) {
console.log(response);
alert("Finish");
// also here i want to read the incoming json
}
You can stop the redirection and perform your Ajax calls by following one of the two methods given below.
Changing the button type to button from submit.
Or calling the JavaScript function on form submit by preventing the default action of submitting the form by utilizing the code snippet below,
I would like to display the (result) of the below code in base64.
The below code shortens inputted url and display its bitly result but i want it to encode the result in base64 instead.
i.e it would have shortened the inputted url to bitly in hidden but will display only the base64 encoded result.
For example, if a particular shortened url result is
http://bit.ly/url
it should display
aHR0cDovL2JpdC5seS91cmw=
jQuery
$(document).ready(function() {
//bit_url function
function bit_url(url) {
var url=url;
var username="username"; // bit.ly Api username
var key="BitLy Key"; //bit.ly Api key
$.ajax({
url:"http://api.bit.ly/v3/shorten",
data:{longUrl:url,apiKey:key,login:username},
dataType:"jsonp",
success:function(v) {
var bit_url=v.data.url;
$("#result").html(''+bit_url+'');
}
});
}
$("#short").click(function() {
var url=$("#url").val();
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var urltest=urlRegex.test(url);
if(urltest) {
bit_url(url);
} else {
alert("Bad URL");
}
});
});
HTML
Enter URL:
<input type="text" placeholder="http://"" name="url" id="url"/>
<input type="submit" id="short" value="Submit"/>
<div id="result"></div>
Would appreciate any help.
You should be able to use btoa() to encode the bit.ly urls. Something like this would work:
$(document).ready(function() {
//bit_url function
function bit_url(url) {
var url=url;
var username="username"; // bit.ly Api username
var key="BitLy Key"; //bit.ly Api key
$.ajax({
url:"http://api.bit.ly/v3/shorten",
data:{longUrl:url,apiKey:key,login:username},
dataType:"jsonp",
success:function(v) {
var bit_url=v.data.url;
var encodedUrl = btoa(bit_url);
console.log(encodedUrl);
$("#result").html(''+bit_url+'');
}
});
}
$("#short").click(function() {
var url=$("#url").val();
var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/ig;
var urltest=urlRegex.test(url);
if(urltest) {
bit_url(url);
} else {
alert("Bad URL");
}
});
});
More information on encoding and decoding base64 in JavaScript is available in the developer docs here:
https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
Hope that helps!
Basically, I have a HTML search form which allows me to search within the database. A JavaScript function is called when the form is submitted but I'm not redirected to the required page.
"Request method 'POST' not supported" is the error message received.
My code:
<form th:object="${devices}" method="POST" onsubmit="return fireAction()">
<input type="text" id="search" name="search" />
<input type="submit" value="Search"/>
</form>
function fireAction() {
var searchInput = document.getElementById('search').value;
var searchFilter = document.getElementById('deviceAttributes').value;
var checkbox = document.getElementById('lastEntry').checked;
alert(searchInput + " " + searchFilter + " " + checkbox);
if (searchInput == "" || searchInput == null) {
alert("Search field cannot be null.");
return false;
} else if (checkbox) {
window.location.href = '/current/' + searchInput
+ '/filter/' + searchFilter;
} else {
window.location.href = '/showForm/' + searchInput
+ '/filter/' + searchFilter;
}
}
#RequestMapping(value = "/showForm/{keyword}/filter/{searchFilter}", method = RequestMethod.POST)
public String showForm(#PathVariable("keyword") String keyword,
#PathVariable("searchFilter") String searchFilter, Model model) {
Devices devices = new Devices();
devices.setSearch(keyword);
devices.setSearchFilter(searchFilter);
model.addAttribute(
"addDevices",
device.findByDevicesName(devices.getSearch(),
devices.getSearchFilter()));
return "showForm";
}
#RequestMapping(value = "/current/{keyword}/filter/{searchFilter}", method = RequestMethod.POST)
public String currentDevices(#PathVariable("keyword") String keyword,
#PathVariable("searchFilter") String searchFilter, ModelMap model) {
model.addAttribute("devices", new Devices());
Devices devices = new Devices();
devices.setSearch(keyword);
devices.setSearchFilter(searchFilter);
List<Devices> newList = device.allDevices();
ListIterator<Devices> iterator = newList.listIterator();
List<Devices> resultList = new ArrayList<Devices>();
while (iterator.hasNext()) {
Devices device = iterator.next();
if (searchLastEntry(device, keyword, searchFilter)) {
resultList.add(device);
}
}
model.addAttribute("iterator2", resultList);
return "current";
}
You don't have a return false in your javascript after executing the window.location.href - So i suspect that after the javascript executes the asynchronous GET request to window.location.href, then the function ends and control is passed back to the form, which just does the normal POST action, but you haven't defined an action URL (which explains the GET then POST requests you say you have seen in the network tab).
Aside, as mentioned in the comments, you probably shouldn't be using POST for a search form - Have a look at http://www.w3schools.com/tags/ref_httpmethods.asp
I have an ASP.NET MVC project and I´m using Cropbox.js : jQuery Image Crop Plugin - http://www.jqueryrain.com/demo/jquery-crop-image-plugin/ to crop an image of a user, but I cannot find how to get the cropped image to the controller.
JavaScript looks like this:
<script type="text/javascript">
window.onload = function () {
var options =
{
imageBox: '.imageBox',
thumbBox: '.thumbBox',
spinner: '.spinner',
imgSrc: 'avatar.png'
}
var cropper;
document.querySelector('#file').addEventListener('change', function () {
var reader = new FileReader();
reader.onload = function (e) {
options.imgSrc = e.target.result;
cropper = new cropbox(options);
}
reader.readAsDataURL(this.files[0]);
this.files = [];
})
document.querySelector('#btnCrop').addEventListener('click', function () {
var img = cropper.getAvatar()
document.querySelector('.cropped').innerHTML += '<img id="Portrait" src="' + img + '">';
})
document.querySelector('#btnZoomIn').addEventListener('click', function () {
cropper.zoomIn();
})
document.querySelector('#btnZoomOut').addEventListener('click', function () {
cropper.zoomOut();
})
};
</script>
I tried to use the following in the controller, but since I´m requesting the file, I´m not sure if it can even work:
HttpPostedFileBase file = Request.Files["Portrait"];
Maybe it would be possible to store the img file from javascript to the model?
My friend has solved it by adding following:
document.getElementById('avatarData').value = img;
To this part of the script:
document.querySelector('#btnCrop').addEventListener('click', function () {
var img = cropper.getAvatar()
document.querySelector('.cropped').innerHTML += '<img src="' + img + '">';
//new added
document.getElementById('avatarData').value = img;
})
Then used invisible input in View form:
<input type="hidden" id="avatarData" name="avatarData" value="">
Now I can catch it in controller:
var file = Request.Form["avatarData"];
And I´ll get:
"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQA..."
To work with this string, there is a very useful question & answer - MVC Convert Base64 String to Image, but ... System.FormatException
I don't know the jQuery Image Crop Plugin, but I think you'll need to do something like that:
Get the image's bytes, convert them to base64 and then send them to ViewController action using Ajax Post.
i thing that you can use AjaxForm or HtmlForm and push it to any action. Then use FormCollection and watch your values. For example in my Captcha generator I override some action for filter:
public class CaptchaValidator : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
RegisterViewModel model = filterContext.ActionParameters["model"] as RegisterViewModel;
if (filterContext.HttpContext.Session["Captcha"] == null || filterContext.HttpContext.Session["Captcha"].ToString() != model.Captcha)
{
filterContext.ActionParameters["captchaValid"] = false;
}
else
{
filterContext.ActionParameters["captchaValid"] = true;
}
base.OnActionExecuting(filterContext);
}
}
and use in your controller:
[CaptchaValidator]
public async Task<ActionResult> Register(RegisterViewModel model, bool captchaValid)
I think that you can here change bool captchaValid to your byte[].
I hope that it can help you :-)
I'm trying to upload a file to my J2eE spring backend. But if I set file required then it does not recognize, so therefor i conclude that it must be the way I try to send it from the front end.
HTML definition:
<form id="filesUploadForm" action="spring/uploadFile" method="post" enctype="multipart/form-data">
<input class="std" id="file" type="file" name="choose">
</form>
Javascript: (Which is triggered from another button)
function uploadFile() {
var url = 'spring/uploadFile';
var formData = $('#filesUploadForm').serialize();
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onload = function() {
console.log('upload complete');
};
xhr.send(formData);
}
If it is relevant: here is the Java code:
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public void uploadFile(#RequestParam(value = "file", required = false) MultipartFile multipartFile) {
String fileName = multipartFile.getOriginalFilename();
System.out.println(fileName);
}
I think you need to change the parameter name in your Java code:
#RequestParam(value = "choose", required = false)