Url.Content for javascript - javascript

I currently use this approach to obtain the correct relative URI (independent of the deployment situation). Razor code (asp.net mvc 3):
#section JavaScript
{
<script type="text/javascript">
var _getUrl = "#Url.Content("~/bla/di/bla")";
</script>
}
Separate js file:
$.ajax({
url: _getUrl,
Do you reckon there is a better approach?

Personally I prefer using HTML5 data-* attributes or including the URL as part of some DOM element that I unobtrusively AJAXify.
The thing is that you never write $.ajax calls flying around like that. You write them to correspond to some DOM events. Like for example clicking of an anchor. In this case it's trivial, you just use an HTML helper to generate this anchor:
#Html.ActionLink("click me", "someAction", "somecontroller", new { id = "123" }, new { #class = "link" })
and then:
$('.link').click(function() {
$.ajax({
url: this.href,
type: 'GET',
success: function(result) {
...
}
});
return false;
});
or maybe you are AJAXifying a form:
#using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Post, new { id = "myForm" }))
{
...
}
and then:
$('#myForm').submit(function() {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(result) {
...
}
});
return false;
});
Another example would be to use HTML5 data-* attributes when an appropriate url is not available on the corresponding DOM element. Suppose that you want to invoke a controller action with AJAX when the selection of a dropdown changes. Think for example cascading ddls.
Here's how your dropdown might look like:
#Html.DropDownListFor(x => x.SelectedValue, Model.Values, new { id = "myDdl", data_url = Url.Action("SomeAction") })
and then:
$('#myDdl').change(function() {
var url = $(this).data('url');
var selectedValue = $(this).val();
$.getJSON(url, { id: selectedValue }, function(result) {
...
});
});
So as you can see you don't really need this _getUrl global javascript variable that you declared in your view.

I would do the following:
Razor C# script before Javascript
#{
var myUrlString = Url.Action("ActionName", new { controller="ControllerName" });
}
JavaScript
$.ajax('#myUrlString',{
// options
});
You could also use Url.RouteUrl or Url.HttpRouteUrl.
EDIT - showing example with separated JS file
Razor
#{
var myServerGeneratedValue = Url.Action("ActionName", new{controller="ControllerName"});
}
<script type="text/javascript">
var myHelperObject = new MyHelperObject();
myHelperObject.Init('#myServerGeneratedValue');
</script>
JS file
var MyHelperObject = function(){
this.Init = function(serverGeneratedValue){
// do something with serverGeneratedValue
};
};

Related

mvc partial view onsubmit form send data from parent view

I am developing MVC 5 App. I have a Parent View that call a Partial View, where user can Load a Image.
On Submit a call a .Ajax defined in Parent view that call Method/Controller.
What I need is to send to the controller data I have in Parent View. Is that Posible?
Here is my code.
Parent View
Partial View
.Ajax Method
$('#formPhoto').submit(function (event) {
event.preventDefault();
if ($(this).valid()) {
var id="aaa";
var formdata = new FormData($(this).get(0));
$.ajax({
url: this.action,
type: this.method,
data:formdata,
processData: false,
contentType: false,
beforeSend: function () {
return true;
},
success: function (result) {
successPhoto();
},
complete: function () {
// alert(3);
// And so on.
}
});
}
return false;
});
I need to send var aa='aaa' in data:
Yes it's possible. So basically I can suggest for you two ways to do what you need:
1st: You could consider putting the form element in the ParentView and change your code a little bit...
2nd: You could recover the data from the parent view and serialize it together to send to your action.
So, from the second option it would be something like:
var parentInformation = 'aaa';
var formdata = new FormData($(this).get(0));
formdata.ExpectedParentOnPropertySide = parentInformation;
Please, I hope this solve your problem

search function in laravel wont work

I have this search bar inside navigation file and it's an enter submit input tag.
I include this file in many pages. but when I enter(submit) it doesn't go to searchResults.blade.php
MY HTML
<input class="searchkey" id="searchkey" type="search" required onkeydown="search(this)">
My JS
$('.searchkey').keydown(function(event) {
var getKeyword = document.getElementById("searchkey").value;
if (event.keyCode == 13) {
$.ajax({
url: "search",
type: "POST",
data:{
getKeyword : getKeyword
},
success: function() {}
});
}
});
MY CONTROLLER
public function multiSearch()
{
$searchKey = Input::get('getKeyword');
$getResults = array();
$getResults = DB::select("SELECT title FROM books WHERE title LIKE '%$searchKey%'");
return View::make('content.searchResults',array('getResults'=>$getResults));
}
MY ROUTES
Route::post('search', 'UserController#multiSearch');
First of all in your ajax callback you should put the view results in some container on the page, i.e.: <div id="search-result"></div> by adding this callback function:
success: function(data) {
$('#search-reasult').html(data);
}
You also have to render the view in your controller like this:
return View::make('content.searchResults',array('getResults'=>$getResults))
->render();

ASP.Net MVC model binding to javascript

The question is pretty straightforward: I use #Html.EditorForModel() to generate fields for my model. Then user fills all these fields and I want to send this field via AJAX, becuase I should do several server's services without page reload.
I googled several approaches, but it seems that there is no standard way to do such things. I mean I do not have an object on client-side that represent model. I found one single library calls JSModel (link) but it seems to be not working. My code for now is:
#model Student
<script src="#Url.Content("~/scripts/jquery-1.12.2.min.js")" type="text/javascript" async="async"></script>
<script src="#Url.Content("~/scripts/Requester.js")" type="text/javascript" async="async"></script>
<script src="#Url.Content("~/scripts/jsmodel.js")" type="text/javascript"></script>
<script type="text/javascript">
var requester = new Requester(#Html.Raw(Json.Encode(new Student())));
function SendSignupRequest() {
requester.SendSignupRequest();
}
</script>
<h2>Student</h2>
<div>
#Html.EditorForModel()
</div>
<input type="button" value="Send" onclick="SendSignupRequest()"/>
Requester.js:
function Requester(rawModel) {
this.modelObj = new JSModel(rawModel);
this.SendSignupRequest = function() {
var model = modelObj.refresh();
var val = model.prop("Name");
alert(val);
}
}
Is there any easy way to serialize a model object in JSON and send it to server, without manually constructing an object with millions of document.getElementById?
View
#using (Html.BeginForm("action", "controller", FormMethod.Post, new { #class = "form-horizontal form-compact ", role = "form", id = "form1" }))
{
}
Java Script
var formdata = $("#form1").serializeArray();
$.ajax({
url: url,
type: 'POST',
data: formdata,
success: function (data) {
}
Controller
public ActionResult action(Model model)
{
//access data here
}
You can serialize your form to a JSON object with jQuery:
var data = $('form').serialize();
(This would, of course, mean wrapping your form elements in a form, which really should be happening anyway.)
Then just pass that data object to the server in the POST request. Something as simple as:
$.post('some/url', data, function(response) {
// success callback
});
without manually constructing an object with millions of document.getElementById
Note that if your object has millions of fields then you may very well encounter other problems here.
Yes you can use form serialize using Jquery
var formData = $('#form').serializeObject();
$.extend(formData, { Contacts : myContacts});
$.extend(formData, { Address : myAddress});
var result = JSON.stringify(formData);
$('#formHiddenField').val(result);
then submit form using:
$.ajax(
url: #Url.Action("post url")
data: myForm.serialize(),
dataType: 'json',
type: 'POST',
success: function(){
})
Why not Ajax.BeginForm() for your purposes. I believe model binding works automatically.

How To implement the Javascript to elements which has been added to head section of HTML By Jquery prepend()?

I have this in my head section.
<script type="text/javascript" src="post.js"></script>
I want this post.js to be also be implemented to the newly created elements.My another js file which is named as main.js have a code that get data from another php file and prepend it in a div with id display.Previous Loaded Div works great with the post.js file but as new elements are prepended, it does not work for new ones. Here is my main.js code which get data from php file and prepend it:
var auto_refresh8 = setInterval(function() {
var id = "id="+$(".ally:first").attr("id");
$.ajax({
type: "POST",
url: "get_post.php",
data: id,
cache: false,
success:function(html){
$('#display').prepend(html);
}
});
},2000);
this jquery ajax request get data from get_post.php file and prepend it to the div display. but the code in post.js doesn't work with this.The data returned by jquery ajax request contains a div with class comm which have to submitted when keypress function acts.
following is the code of post.js :
$(document).ready( function() {
$(".comm").keypress(function(e) {
if(e.which == 13) {
var id = $(this).attr("id");
var data = 'id=' + id;
var post = $(this).val();
var data1 = 'comment='+post;
var wholedata = data+'&'+data1;
$(this).blur();
$.ajax({
type: "POST",
url: "c_insert.php",
data: wholedata,
cache: false,
success:function(html){
$('.class_all'+id).append(html);
}
});
return false;
}
});
});
Use a delegate to handle the event in post.js file instead. See the jQuery documentation for more information.
Something like this should do it:
$('#display').on('keypress', '.comm', function (e) {
if(e.which == 13) {
// Do code on event
}
});
Note that the "on" function should only be used if you are using jQuery version 1.7 or later. Previous versions uses the function "delegate".
edit Changed $(document).on(...) to $('#display').on(...) since all '.comm'-elements are children of '#display'.

Calling ASP.NET MVC Action Methods from JavaScript

I have sample code like this:
<div class="cart">
<a onclick="addToCart('#Model.productId');" class="button"><span>Add to Cart</span></a>
</div>
<div class="wishlist">
<a onclick="addToWishList('#Model.productId');">Add to Wish List</a>
</div>
<div class="compare">
<a onclick="addToCompare('#Model.productId');">Add to Compare</a>
</div>
How can I write JavaScript code to call the controller action method?
Use jQuery ajax:
function AddToCart(id)
{
$.ajax({
url: 'urlToController',
data: { id: id }
}).done(function() {
alert('Added');
});
}
http://api.jquery.com/jQuery.ajax/
Simply call your Action Method by using Javascript as shown below:
var id = model.Id; //if you want to pass an Id parameter
window.location.href = '#Url.Action("Action", "Controller")/' + id;
You are calling the addToCart method and passing the product id. Now you may use jQuery ajax to pass that data to your server side action method.d
jQuery post is the short version of jQuery ajax.
function addToCart(id)
{
$.post('#Url.Action("Add","Cart")',{id:id } function(data) {
//do whatever with the result.
});
}
If you want more options like success callbacks and error handling, use jQuery ajax,
function addToCart(id)
{
$.ajax({
url: '#Url.Action("Add","Cart")',
data: { id: id },
success: function(data){
//call is successfully completed and we got result in data
},
error:function (xhr, ajaxOptions, thrownError){
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
}
When making ajax calls, I strongly recommend using the Html helper method such as Url.Action to generate the path to your action methods.
This will work if your code is in a razor view because Url.Action will be executed by razor at server side and that c# expression will be replaced with the correct relative path. But if you are using your jQuery code in your external js file, You may consider the approach mentioned in this answer.
If you do not need much customization and seek for simpleness, you can do it with built-in way - AjaxExtensions.ActionLink method.
<div class="cart">
#Ajax.ActionLink("Add To Cart", "AddToCart", new { productId = Model.productId }, new AjaxOptions() { HttpMethod = "Post" });
</div>
That MSDN link is must-read for all the possible overloads of this method and parameters of AjaxOptions class. Actually, you can use confirmation, change http method, set OnSuccess and OnFailure clients scripts and so on
If you want to call an action from your JavaScript, one way is to embed your JavaScript code, inside your view (.cshtml file for example), and then, use Razor, to create a URL of that action:
$(function(){
$('#sampleDiv').click(function(){
/*
While this code is JavaScript, but because it's embedded inside
a cshtml file, we can use Razor, and create the URL of the action
Don't forget to add '' around the url because it has to become a
valid string in the final webpage
*/
var url = '#Url.Action("ActionName", "Controller")';
});
});
Javascript Function
function AddToCart(id) {
$.ajax({
url: '#Url.Action("AddToCart", "ControllerName")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'id': id },
success: function (results) {
alert(results)
},
error: function () {
alert('Error occured');
}
});
}
Controller Method to call
[HttpGet]
public JsonResult AddToCart(string id)
{
string newId = id;
return Json(newId, JsonRequestBehavior.AllowGet);
}
You can simply add this when you are using same controller to redirect
var url = "YourActionName?parameterName=" + parameterValue;
window.location.href = url;
You can set up your element with
value="#model.productId"
and
onclick= addToWishList(this.value);
I am using this way, and worked perfectly:
//call controller funcntion from js
function insertDB(username,phone,email,code,filename) {
var formdata = new FormData(); //FormData object
//Iterating through each files selected in fileInput
formdata.append("username", username);
formdata.append("phone", phone);
formdata.append("email", email);
formdata.append("code", code);
formdata.append("filename", filename);
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/InsertToDB');//controller/action
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
//if success
}
}
}
in Controller:
public void InsertToDB(string username, string phone, string email, string code, string filename)
{
//this.resumeRepository.Entity.Create(
// new Resume
// {
// }
// );
var resume_results = Request.Form.Keys;
resume_results.Add("");
}
you can find the keys (Request.Form.Keys), or use it directly from parameters.
You can easily make a <a> link in your view.
<a hidden asp-controller="Home" asp-action="Privacy" id="link"></a>
then in you javascript code use this:
location.href = document.getElementById('link').href;

Categories