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
Related
I have a button that when you click it, it will show a confirmation box. If the user clicks 'ok', the word 'reached' would display inside of the div named 'EventData'.
So far the confirmation box shows when I click the button but 'EventData' won't show the word 'reached' when I confirm it.
*the 'event_id' has a value
I think the problem is with the url part where it won't go in the function
Route:
Route::post('/ArchiveEventPosts','AdminController#ArchiveEventposts')->name('ArchiveEventposts');
Script:
$(document).on('click', '.archive', function() {
var event_id = $(this).attr('event_id');
var x = confirm("Are you sure you want to archive this record?");
if (x) {
$.ajax({
method: "POST",
url: '{{ route("ArchiveEventposts") }}',
data: {
event_id: event_id
},
success: function(data) {
$('#EventData').html(data);
alert('Record Archived');
}
});
}
});
Function in the controller:
public function ArchiveEventposts(Request $request)
{
echo 'Reached';
}
You might need to change the way your route is assigned. What you are doing is assigning a plain string to the URL with a single quotation mark. Try like this:
var archiveEventpostsRoute = "{{ route('ArchiveEventposts') }}";
and below
url: archiveEventpostsRoute,
Also, make sure that your controller is returning the proper data, as stated in the other answer:
public function ArchiveEventposts(Request $request)
{
return response()->json(["message" => "Reached"]);
}
Your controller method is not returning any data; it's simply printing the word "Reached".
You'll need to change the function to something like this:
public function ArchiveEventposts(Request $request)
{
return response()->json(["message" => "Reached"]);
}
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.
So, I have a view with a chosen search box, a button "Add" (btn-default) and a button "Edit" (breadcrumb) . When I click the Add button, the ajax sent me a table with the values (in this case, funcionaries) selected in the chosen text box.
I want that, when I click on the Edit button, send the chosen values (can be one, or hundreds of values) to another controller to return another view.
Don't want to use ajax because I want to use a new view on totally.
On the controller side, when I send the data with javascript, I always get null. Why?
View
<script>
$(document).ready(function () {
$(".btn-default").on("click", function (event, params) {
$.ajax({
url: '#Url.Action("EditarPonderacoesEspecial", "Sorteios")',
type: 'POST',
dataType: 'html',
cache: false,
traditional: true,
data: { bdoIds: $(".chosen-select").val() },
success: function (responseText, textStatus, XMLHttpRequest) {
$("#MyDiv").empty();
$("#MyDiv").html(responseText);
},
error: function () { }
})
});
$(".breadcrumb").on("click",function (event, params) {
bdoIds = $(".chosen-select").val();
$.post("/Sorteios/EditarPonderacoesEspecialSecond/", bdoIds);
});
});
Controller
public ActionResult EditarPonderacoesEspecialSecond(string[] bdoIds)
{
//do whatever I want with the bdoIds
return View();
}
I had tried many different ways, but the controller always receive the parameter as null. What I am doing wrong? Thanks!
Your controller action is expecting an array of strings.
Assuming .chosen-select is a select list as that part is missing from the question.
First read the selected values into an object as follows:
var selectedValues = [];
$(".chosen-select :selected").each(function() {
selectedValues.push($(this).attr('value'));
});
Then send them as follows:
$(".breadcrumb").on("click",function (event, params) {
var selectedValues = [];
$(".chosen-select :selected").each(function() {
selectedValues.push($(this).attr('value'));
});
$.post("/Sorteios/EditarPonderacoesEspecialSecond/", { bdoIds: selectedValues });
});
Declare Global array like
var SelectedArray = new Array();
When you select multiple selectlist item each time push value in SelectedArray
$('#ChosenId').chosen().change(function () {
SelectedArray = $('#ChosenId').chosen().val();
});
Then your ajax data is like
data: { bdoIds: SelectedArray },
My Model has fields which are displayed on the screen, as well as a List which is displayed in a grid on the screen. I have an Add button, which shows a modal popup (without a postback), that allows the user to enter a few fields, and then clicks 'Save'. At the moment, I use a JSON call back to my controller to save the data. I then reload the screen, and the new item appears in the grid, as it was saved to the database, and the Model reloaded.
Problem is, if the user has made any changes to the main details in the model, they're lost, because all the JSON call did was save a new item to the database, and redirect to the main screen which reloads.
What I need to rather do is somehow, add the new item from the popup, to the main Model, and then reload the grid, without saving to the database at all, and without a postback.
My javascript for posting the data from the view looks like this:
<script type="text/javascript">
$(document).ready(function () {
$('.btnSubmitNewCard').click(function () {
var data = { cardNumber: $('.txtNewCardNumber').val(), cardHolder: $('.txtNewCardHolder').val(), expiryMonth: $('.txtNewExpiryMonth').val(), expiryYear: $('.txtNewExpiryYear').val(), active: $('.txtNewActive').val(), accountId: $('.Id').val() };
$.ajax({
url: '#Url.Action("SaveBankCard", "BankAccount")',
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
cache: false,
async: true,
success: function (result) {
if (result.Success == 'true') {
window.location = '#Url.Action("EditBankAccount", "BankAccount", new { bankAccountId = Model.Id })';
} else {
alert(result.Message);
}
},
error: function () {
alert("Oh no");
}
});
});
});
</script>
And then the controller method that handles this, looks like this:
public JsonResult SaveBankCard(string cardNumber, string cardHolder, int expiryMonth, int expiryYear, string active, int accountId)
{
var card = new AccountCardDto
{
Id = 0,
AccountId = accountId,
Active = active == "on",
CardHolderName = cardHolder,
CardNumber = cardNumber,
ExpiryDate = new DateTime(2000 + expiryYear, expiryMonth, 1)
};
var id = new BankAccountService().SaveCard(card);
var result = new { Success = "true", Message = "Saved", NewId = id };
var r = new JsonResult
{
Data = result
};
return r;
}
So, the data is saved in the controller, and then the Javascript redirects to roload the whole screen. Can this be changed to rather save the data to the models' List client side, and then the whole model with changes and additions get saved via the one Save button on my screen? Is it possible to add to the Model's List client side?
try json script like this
$('#ddlCompany').change(function () {
//var URL = $('#Enrollform').data('fetchproduct');
$.getJSON('/EnrollmentForm/fetchproduct/' + $('#ddlCompany').val(), function (data) {
var items = '<option>Select a Product</option>';
$.each(data, function (i, product) {
items += "<option value='" + product.Value + "'>" + product.Text + "_" + product.Value + "</option>";
});
$('#ddlProduct').html(items);
});
});
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.