This is my Post function something like this:
function Post(data) {
var self = this;
data = data || {};
self.PostId = data.PostId;
self.Message = ko.observable(data.Message || "");
self.PostedBy = data.PostedBy || "";
self.NeighbourhoodId = data.id || "";
This is my simple function in knockout. Here at the last line u can see, data: ko.toJson(post)
self.addPost = function () {
var post = new Post();
post.Message(self.newMessage());
return $.ajax({
url: postApiUrl,
dataType: "json",
contentType: "application/json",
cache: false,
type: 'POST',
data: ko.toJSON(post)
})
.done(function (result) {
self.posts.splice(0, 0, new Post(result));
self.newMessage('');
})
.fail(function () {
error('unable to add post');
});
}
Now, along with this, i want to pass dropdown selected id something like this:
data: { id: $("#Locations").val() }
Right now, i have tried using this:
data:{post: ko.toJSON(post), id: $("#Locations").val() }
but in controller, post: ko.toJSon(post) is sending nothing however i am getting id of selected dropdown but not the message property of post parameter.
If i use this line:
data: ko.toJSON(post)
then i can get every property of post parameter but then id is null so, how to deal with this.Plzz Plzz help me out.Debugger is showing nothing useful information.My Post Controller is:
public JsonResult PostPost(Post post, int? id)
{
post.PostedBy = User.Identity.GetUserId<int>();
post.NeighbourhoodId = id;
db.Posts.Add(post);
db.SaveChanges();
var usr = db.Users.FirstOrDefault(x => x.Id == post.PostedBy);
var ret = new
{
Message = post.Message,
PostedBy = post.PostedBy,
NeighbourhoodId = post.NeighbourhoodId
};
return Json( ret,JsonRequestBehavior.AllowGet);
}
on my view page,this is the button on which click event i fired addPost function
<input type="button" data-url="/Wall/SavePost" id="btnShare" value="Share" data-bind="click: addPost">
along with this, dropdown for sending id is something like this:
#Html.DropDownList("Locations", ViewBag.NeighbourhoodId as SelectList, "Select a location")
<script type="text/javascript">
$(document).ready(function () {
$("#btnShare").click(function () {
var locationSelected = $("#Locations").val();
var url = '#Url.Action("PostPost", "Post")';
$.post(url, { id: locationSelected },
function (data) {
});
});
});
</script>
Plzz someone help me out.I am not getting what to do from here.
Related
I posted this yesterday but i may not have explained my situation well.
I have 3 grids on a page that are built dynamically through JavaScript.
I then have 3 separate JavaScript methods to set a session when a row is clicked in a certain grid.
Once the session is set i would like it to navigate to the next page.
Here is what i have
OnClick event
$('#clinician-planned').on('click', 'tbody>tr>td:not(:last-child):not(:first-child)', function () {
var ID = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
var Location = '#Url.Action("SetPASession", "Clinician")';
AjaxCall(Location, ID);
});
$('#clinician-recent').on('click', 'tbody>tr>td:not(:last-child):not(:first-child)', function () {
var ID = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
var Location = '#Url.Action("SetRDSession", "Clinician")';
AjaxCall(Location, ID);
});
$('#clinician-theatre').on('click', 'tbody>tr>td:not(:last-child):not(:first-child)', function () {
var ID = $(this).closest("tr").children("td.grid__col--id").find("[name=patient-link]").text().trim();
var Location = '#Url.Action("SetTESession", "Clinician")';
AjaxCall(Location, ID);
});
AJAX Post To Controller
function AjaxCall(Location, ID) {
alert('1');
$.ajax({
type: 'POST',
url: Location,
dataType: 'text',
async: false,
contentType: 'application/json; charset=utf-8',
error: function (response) { alert(JSON.stringify(response)); }
}).done(function (response) {
alert('2');
location.href = "#Url.Action("Summary", "Patient")" + "/" + ID;
});
}
Here are the controller methods
public ActionResult SetPASession()
{
Session.Remove("Clinician");
Session["Clinician"] = "pa";
return Json(null);
}
public ActionResult SetRDSession()
{
Session.Remove("Clinician");
Session["Clinician"] = "rd";
return Json(null);
}
public ActionResult SetTESession()
{
Session.Remove("Clinician");
Session["Clinician"] = "te";
return Json(null);
}
The problem i have is when the row is clicked "alert('1'); shows instantly, however it seems like it takes a while and waits for all grids to be populated before the 2nd alert appears. I have tried putting async: false, but this doesnt seem to work.
Any ideas would be much appreciated.
I have this div
<div class='additional_comments'>
<input type="text" id='additional_comments_box', maxlength="200"/>
</div>
Which will only sometimes appear on the page if jinja renders it with an if statement.
This is the javascript i have to send an ajax request:
$(document).ready(function() {
var button = $("#send");
$(button).click(function() {
var vals = [];
$("#answers :input").each(function(index) {
vals.push($(this).val());
});
vals = JSON.stringify(vals);
console.log(vals);
var comment = $('#additional_comments_box').val();
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'vals': vals,
'comment': comment,
},
dataType: 'json',
success: function (data) {
location.href = data.url;//<--Redirect on success
}
});
});
});
As you can see i get the comments div, and I want to add it to data in my ajax request, however if it doesnt exist, how do I stop it being added.
Thanks
You can use .length property to check elements exists based on it populate the object.
//Define object
var data = {};
//Populate vals
data.vals = $("#answers :input").each(function (index) {
return $(this).val();
});
//Check element exists
var cbox = $('#additional_comments_box');
if (cbox.length){
//Define comment
data.comment = cbox.val();
}
$.ajax({
data: JSON.stringify(data)
});
I am trying to pass data from a view to a controller using parameters.
Now I am running a few difficulities. I am trying to pass those parameters once I select a row from a table and press on a button which has a onclick method to ShowTasks()
The C# controller:
[Route("/service/delivery/{id}/{shopdoccode}/{regdate}")]
public ActionResult Delivery(string id, string shopdoccode, string regdate)
{
//do stuf
}
The Javascript function when user clicks on button:
function ShowTasks() {
//Dear Stackoverflow > This works, this is for selecting a row in the table
var $selectedRow = $(".highlight");
if ($selectedRow.length == 1) {
var dcColumn = 0;
var rdColumn = 1;
var shopdoccodeColumn = 3;
//assigning name to the colomn value
var id = $selectedRow[0].children[dcColumn].innerText.trim();
var regdate = $selectedRow[0].children[rdColumn].innerText.trim();
var shopdoccode = $selectedRow[0].children[shopdoccodeColumn].innerText.trim();
//ajax
if (id && regdate && shopdoccode) {
$.ajax({
type: 'POST',
url: '#Url.Action("service", "delivery" ,new { id = "id", shopdoccode = "shopdoccode", regdate = "regdate" })',
data: { id, regdate, shopdoccode },
success: function (data) {
if (data.success) {
console.log("Succes");
}
},
error: function (data) {
console.log("Error");
}
});
}
}
}
What have I done so far? Sitting for hours trying to find a way to give the parameters to my controller so I can invoke a SQL stored procedure.
Unforntunately I can not simply use a hidden form for this.
Also this was quite helpful:
Url.Action parameters?
#sleeyuen
Looks to me like your Url.Action has its parameters in the wrong order. Change it to:
url: '#Url.Action("delivery", "service", new { id = "id", shopdoccode = "shopdoccode", regdate = "regdate" })',
Here's the appropriate overload that you want:
Action(String, String, Object) with actionName, controllerName, and routeValues, in that order.
You can not *.js or *.html file wrtie razor code.
#Url.Action(string actionName,string controllerName,object routeValues)
The above code can only be used *.cshtml file.
test with Url.RouteUrl instead of Url.Action
I am trying to show the details of each Student with Json and I think it is not going to the ajax part.
It shows the id and the url when I console.log() them, but I get this error message for the ajax part
I don't know what's missing or where is the issue?
This is my html link
#Html.ActionLink("Details", "StudentDetails", new { id = item.ID }, new { #class = "modalDetails", #id = item.ID })
script
<script type="text/javascript">
$(function () {
$(".modalDetails").click(function (e) {
e.preventDefault(); //stop the default action upon click
var id = $(this).attr('id');
console.log(id);
var url = $(this).attr("href");
console.log(url);
$.ajax({
type: 'GET',
data: { id: id },
dataType: "json",
url: url,
success: function (data) {
$(".modalDetails").append('<span> First Name: ' + data.firstName + '</span></br>');
console.log("success");
}
});
$('#myModal').modal('show'); // show the modal pop up
});
});
</script>
StudentController
public JsonResult StudentDetails(int id)
{
Student student = studentRepository.GetStudentByID(id);
var json = new{
firstName = student.FirstMidName
};
return Json(json, JsonRequestBehavior.AllowGet);
}
Everything was fine, except that I needed to build the solution and append the details to the modal-body. Sometimes it is just a simple fix.
I'm having some problem with passing a javascript array to the controller. I have several checkboxes on my View, when a checkbox is checked, its ID will be saved to an array and then I need to use that array in the controller. Here are the code:
VIEW:
<script type="text/javascript">
var selectedSearchUsers = new Array();
$(document).ready(function () {
$("#userSearch").click(function () {
selectedSearchUsers.length = 0;
ShowLoading();
$.ajax({
type: "POST",
url: '/manage/searchusers',
dataType: "json",
data: $("#userSearchForm").serialize(),
success: function (result) { UserSearchSuccess(result); },
cache: false,
complete: function () { HideLoading(); }
});
});
$(".userSearchOption").live("change", function () {
var box = $(this);
var id = box.attr("dataId");
var checked = box.attr("checked");
if (checked) {
selectedSearchUsers.push(id);
}
else {
selectedSearchUsers.splice(selectedSearchUsers.indexOf(id), 1);
}
});
$("#Send").click(function () {
var postUserIDs = { values: selectedSearchUsers };
ShowLoading();
$.post("/Manage/ComposeMessage",
postUserIDs,
function (data) { }, "json");
});
});
</script>
When the "Send" button is clicked, I want to pass the selectedSearchUsers to the "ComposeMessage" action. Here is the Action code:
public JsonResult ComposeMessage(List<String> values)
{
//int count = selectedSearchUsers.Length;
string count = values.Count.ToString();
return Json(count);
}
However, the List values is always null. Any idea why?
Thank you very much.
You might try changing the controller's action method to this:
[HttpPost]
public JsonResult ComposeMessage(string values)
{
JavaScriptSerializer jass = new JavaScriptSerializer;
AnyClass myobj = jass.Deserialize<AnyClass>((string)values);
...
...
}
I believe that you have to take the JSON data in as a string and do the conversion
manually. Hope it helps. Cheers.