I am trying to call the propDetails function and pass an ID to it. Then pass the same ID to the Static controller but I keep on getting an error: "id = id" (second ID doesn't exist).
I am sorry for this silly question and I can't figure out what I am doing wrong...
function propDetails(id) {
var $detailDiv = $('#detailsDiv'), url = $(this).data('url');
$.get( '#Url.Action("PropDetails", "Static", new { id = id })', function(data) {
$('#detailsDiv').html(data);
});
}
Any guidance would be greatly appreciate.
The id variable is not available in the Razor helper, what you can do is concatenate the id after the Url.Action helper has finished:
function propDetails(id) {
var $detailDiv = $('#detailsDiv'), url = $(this).data('url');
$.get('#Url.Action("PropDetails", "Static")' + id, function(data) {
$('#detailsDiv').html(data);
});
}
In the long run you would want to render a form to serialize your id as part of the request, written as $("form").serialize().
It is much easier to append more fields to an action that uses a complex type as a parameter. Your new code would look as follows:
$.get($detailDiv.find("form").attr("action"),$detailDiv.find("form").serialize(), function(data){
$('detailsDiv').html(data);
});
Your form object would be created in your HTTPGET request in MVC, returning the view with your built #Html.BeginForm() helper, which is part of innerHtml of detailsDiv, that can then be serialized using $("form").serialize()
I hope this is clear and fully answers how to fix the issue. I will modify if it is off base and adds more muddle to the mix of Javascript and MVC.
Related
Here is what I am trying to do. I want to be able to call an html action and pass in some data as an object parameter. The only thing is this data needs to be returned from a javascript function.
Here is what I am trying to do:
#Html.Action("someAction", "someController", new { passedData = GetDropDownData() })
<script>
function GetDropDownData() {
var data = "test";
return data;
}
</script>
Basically I am trying to pass some drop down data from a control to a partial view being rendered with the #Html.Action(). I want to be able to pass this string to the partial view somehow so I figured I could use JS to pull the drop down data and return it as an object parameter when rendering the page?
Let me know if you have any suggestions or a better way to go about this.
Thank you!
This is not possible the way you're doing it, because razor views are compiled on server side, while javascript is client side. Therefore, the views are already compiled, while javascript runs during runtime. One way to do it is to use ajax to pass variables from javascript to an action in the controller as query parameters or body values. You could achieve that by creating a button or link:
<a href='#' id='clickMe'>Click me</a>
And hooking up jQuery to do the job:
<script>
$(document).ready(function(){
$('#clickMe').click(function(){
$.ajax({
type: "POST",
url: '#Url.Action("Action", "Controller")',
data: {
passedData: GetDropDownData()
},
success: function(response){
$('#placeholderForPartialView').html(response);
}
});
});
});
</script>
It would look something like this depending on your method (GET or POST) type.
Here I assume that you return Partial view as a result and replace the contents of #placeholderForPartialView div with the returned view. Please correct me if I'm wrong.
Iam trying to post an Javascript Object via php, but i cant get the value in PHP, iam using laravel framework.
my array,
[type: "sadf", level: "sadfasdf"]
javascript code,
var data_push = Array();
$('form').on('change', 'select, textarea, input', function(t,s){
var key = $(this).attr('id');
var value = $(this).val();
data_push[key] = value;
});
$("#submit").click(function(){
$.post("{!! URL::to('test') !!}", {
_token : tempcsrf,
req_data : data_push
},
function (resp, textStatus, jqXHR) {
alert(resp);
});
});
php code,
public function workbook_save(Request $request_data)
{
$require_data = $request_data->req_data;
print_r($require_data);
}
Tried also JSON.stringfy(data_push) ,json_decode but no luck, i cant get the Javascript object in php, donno what iam doing wrong here, pls advice.
This is what your JS does:
Creates an array
Sets up an event handler to populate the array when things change in the form
Posts the (empty) array to the server
Later on, things will change in the form and data will be put in the array.
The server knows nothing about this because you already sent its contents.
You need to change your logic so you only make the POST request when you are ready to send the data.
I have an ajax post function:
$(".button").click(function(){
var postData = ..some data..
var targetDiv = $(this).closest(".someDiv");
$.post(doucemnt.location, postData, function(data) {
content = ... How to find targetDiv inside data here? ..
targetDiv.html(content);
});
});
The data returned from post will be the whole webpage, and I need to filter it and only get the div I want to refresh. I do not want to use any selectors by ID or class, because there are many copies of the "someDiv" and "button" inside each div, so I want to just get the div object of currently clicked button and search for it in callback data.
is that possible?
I'm not sure I fully understand your question, so forgive me if I'm way off.
I think (if nothing else) this might help give you some ideas. I will parse through the response data looking for a specific 'hook'. Then return just that chunk of data...
JavaScript:
$('.button').click(function (event) {
// This would be your (real) ajax call.
doAjaxPost('www.location.com', postData, function (response) {
var $refresh = $($.parseHTML(response)).filter('#refresh');
$('#content').html($refresh);
});
});
JSFiddle
I am using backbone for the first time and I am really struggling to get it to function correctly with a JSON data file.
I have a model Like so:
window.Test = Backbone.Model.extend({
defaults: {
id: null,
name: null,
},
url: function() {
return 'json/test.json/this.id';
},
initialize: function(){
}
});
When a test item is clicked I then try to bring up the details of the pacific model that was clicked by doing
testDetails: function (id) {
var test = new Test();
test.id = id;
test.fetch({ success: function(data) { alert(JSON.stringify(data))}});
},
However this does not work, I am unable to correctly say "get the JSON element with the passed ID"
Can anyone please show me how to correctly structure the models URL to pull the element with the ID.
Thanks
The problem here is that you're treating your JSON data file like a call to a server. That won't work and it's the reason you're getting a 404. If you're accessing a file locally, you have to load the file first. You can do this with jQuery using the .getJSON() method, or if the file's static, just load it into memory with a script block (though you'll probably need to assign a var in the file). Most likely, you'll use jQuery. An example of this can be found here:
Using Jquery to get JSON objects from local file.
If this is an array of JSON, you can load the array into a collection, and use the "at" method to access the particular element by id. If it's entirely JSON, you'll have to create a custom parser.
your url is incorrect for one. you are returning the literal string 'this.id'. you probably want to do something more along the lines of
url: function () {
return 'json/test.json/' + this.id;
}
I would start by fixing your url function:
url: function() {
return 'json/test.json/' + this.get('id');
}
The way you have it now, every fetch request, regardless of the model's id, is going to /json/test.json/test.id
This seems to be quite a common theme and a few people have given some very constructive answers, but I'm still struggling to get my attempt to work.
The problem is much the same as this one for example, except that I'm only trying to send a single complex object instead of an array.
My controller looks like this:
[AcceptVerbs (HttpVerbs.Put)]
[Authorize]
[JsonFilter(Param="Designer", JsonDataType=typeof(Designer))]
public JsonResult SaveProfile(Designer Profile)
{
ProfileRepository Repo = new ProfileRepository();
Designer d = Repo.GetById(Profile.ID);
d.Comments = Profile.Comments;
d.DisplayName = Profile.DisplayName;
d.Email = Profile.Email;
d.FirstName = Profile.FirstName;
d.LastName = Profile.LastName;
Repo.Update(d);
return Json(Profile);
}
The code for retrieving the page data and posting it looks like this:
$('#save-profile').click(function () {
var Profile = {};
var context = $('#profile-data')[0];
$('span', context).each(function () {
Profile[this.id] = $(this).text();
});
Profile.ID = $('h3', context).attr('id');
console.log(Profile);
//var DTO = { 'Profile': Profile };
$.ajax({
type: "PUT",
url: "/Home/SaveProfile",
data: { 'Profile': Profile },
success: function (data) {
console.log(data);
}
});
});
The object is being correctly created and posted to the server (I've tried using POST and PUT, by the way), the server appears to be receiving an object instance, but the properties are - as usual - all null.
What am I missing? I've tried using the approach (adapted) from the example question linked above, but still don't seem to be getting any closer to the solution. Any help appreciated.
As it turns out, there's nothing wrong with the ActionResult method itself and neither is there any issue with the JavaScript object or Ajax post. The problem actually lies in the custom filter that decorates the ActionResult and the parameter being set for its param value.
The following attribute has a parameter of "Designer" set for the name of the parameter I'm trying to pass in. I've supplied this as both the parameter name and the type.
[JsonFilter(Param="Designer", JsonDataType=typeof(Designer))]
The correct version should be:
[JsonFilter(Param="Profile", JsonDataType=typeof(Designer))]