Cannot pass parameters from View to Controller via JavaScript - javascript

Although I manage to send the grid's selected row id to the controller, the url for opening action view cannot be built up (it is created /Controller/Action instead of /Controller/Action/id. So, when I try to open the view with /Controller/Action/id it is open, but it cannot be opened by button click as below.
View:
<input type="button" id="btn" name="name" value="send to Server!" />
<script>
$('#btn').click(function () {
var items = {};
var grid = $('#Grid').data('kendoGrid');
var selectedElements = grid.select();
var item = grid.dataItem(selectedElements[0]);
$.ajax({
type: "POST",
data: item.ID, //I obtained the id properly
url: '#Url.Action("CreateParticipant", "Training")',
success: function (result) {
//console.log(result);
}
})
})
</script>
Controller:
// GET: /Training/CreateParticipant/5
public ActionResult CreateParticipant(int? id)
{
Training training = repository.Trainings.FirstOrDefault(m => m.ID == id);
if (training == null)
{
return HttpNotFound();
}
var trainingParticipantViewModel = new TrainingParticipantViewModel(training);
return View(trainingParticipantViewModel);
}
Route.config:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
//defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
defaults: new { controller = "Multiplier", action = "Index", id = UrlParameter.Optional }
);
}
}
Is there another example as above to pass the parameters or is there any mistake on the code above? Thanks in advance.

Javascript
$('#btn').on("click",function () {
var items = {};
var grid = $('#Grid').data('kendoGrid');
var selectedElements = grid.select();
var item = grid.dataItem(selectedElements[0]);
$.ajax({
type: "GET",
data: item.ID, //I obtained the id properly
url: '#Url.Action("CreateParticipant", "Training")/'+item.ID,
datatype:'html',
success: function (result) {
alert(result)
}
})
})
Or use
$('#btn').on("click",function () {
var items = {};
var grid = $('#Grid').data('kendoGrid');
var selectedElements = grid.select();
var item = grid.dataItem(selectedElements[0]);
window.location.href= '#Url.Action("CreateParticipant", "Training")/'+item.ID;
});
Hope this helps.

.ToolBar(toolbar =>
{
toolbar.Template(#<text>
<div class="toolbar">
#(Html.Kendo().Button()
.Name("addbtn")
.Content("Add New")
.HtmlAttributes(new { type = "button", #class = "k-primary k-button k-button-icontext js-myKendoButton", #data_id = #Model.YourID, onclick = "onClick()" })
)
</div>
</text>);
})
And then you will grab the data-attribute with jQuery.
$('.js-myKendoButton').attr('data-id');
More here: How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

<script>
$('#btn').on("click",function () {
var items = {};
var grid = $('#Grid').data('kendoGrid');
var selectedElements = grid.select();
var item = grid.dataItem(selectedElements[0]);
$.ajax({
type: "POST",
data: {ID : item.ID}, //I obtained the id properly
url: '#Url.Action("CreateParticipant", "Training")',
success: function (result) {
//console.log(result);
}
})
})
</script>
use this ,i hope this will be help you

Related

post array from jQuery to yii2 session

How I can post a JavaScript array , and to write him to the session I opened in the Controller
This is my view where I save the id`s in an array
<script type="text/javascript">
$(document).ready(function () {
var data = [];
s = 0;
$('.custombtn').click(function () {
var id = $(this).attr("value");
data.push(id);
console.log(data);
});
});
And This is my Controller where I open a session , but cant figure out how I can post the array to be stored in the session
public function actionShop() {
if (!Yii::$app->session->isActive) {
Yii::$app->session->open();
$query = Stock::find();
$pagination = new Pagination([
'defaultPageSize' => 6,
'totalCount' => $query->count(),
]);
$stock = $query->orderBy('id')
->offset($pagination->offset)
->limit($pagination->limit)
->all();
}
return $this->render('shop', [
'stock' => $stock,
'pagination' => $pagination,
]);
}
worked with inserting Ajax
$(document).ready(function () {
var data = [];
$('.custombtn').click(function () {
var id = $(this).attr("value");
data.push(id);
console.log(data);
$.ajax({
type: 'POST',
url: 'controllers/StockController.php',
data: {data: data},
dataType: 'json'
});
});
});

ajax call function with parameters in mvc

I am very new to this, what I am trying to do is use ajax to call a controller function from view, this is my controller.
public ActionResult EditSiteGetContact(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
using (var db = SiteUtil.NewDb)
{
var owner = db.Contacts.Include(o => o.Id).FirstOrDefault(o => o.Id == id);
if (owner == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var orgViewModel = OrgViewModel.ToViewModel(owner);
return View("Edit", orgViewModel);
}
}
and this is the view where I want to show the data
<div class="form-group" id="alanTest">
<label class="control-label col-md-2">Contact Person</label>
<div class="col-md-6 form-inline">
#Html.TextBoxFor(model => model.Owner.Name, new { #class = "form-control", style = "width:200px", type = "text" })
<img src="~/Images/help-icon.png" class="tooltips" id="ContactPerson_Tooltip" title="lol">
#Html.ValidationMessageFor(model => model.Owner.Name)
</div>
</div>
my ajax part:
$("#alanTest").ready(function(){
var alanURL = "#Url.Action("EditSiteGetContact","Org")";
var contactId = #Model.Org.ContactId;
$.ajax({
type:"POST",
url:alanURL,
data:{
id:contactId
},
success:function(data){
alert(data);
},
error: function(){
alert("error");
}
});
});
i got "error" message..
Add [HttpPost] attribute before EditSiteGetContact(int? id).
In the ajax function change
var contactId = #Model.Org.ContactId; to var contactId = "#Model.Org.ContactId";
Please see below code. It may help you.
$("#alanTest").ready(function(){
var alanURL = "#Url.Action("EditSiteGetContact","Org")";
var contactId = "#Model.Org.ContactId";
$.ajax({
type:"POST",
url:alanURL,
data:{
id:contactId
},
success:function(data){
alert(data);
},
error: function(){
alert("error");
}
});
});

Controller not receiver parameter passed by ajax POST in .Net MVC

I want to make an ajax shopping cart, the GetCarts and AddCart all working, but the RemoveRow not
receiver the parameter "strms". When alert(strms) in removeRow(strms) js function, it show right value
of the book id (equal 8). But in the CartController/RemoveRow debug, the strms value is NULL.
I think it's can be a problem with the routing, but I think my route configs are right!
Please help me.
The view is _Layout.cshtml, which contain js code
The controller is CartController
My RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Sach", action = "Detail", id = "7" }
);
routes.MapRoute(
"Cart",
"{controller}/{category}/{ms}/{sl}",
new { controller = "Cart", action = "AddCart", ms = UrlParameter.Optional, sl = UrlParameter.Optional }
);
routes.MapRoute(
"CartRemoveRow",
"{controller}/{action}/{ms}",
new { controller = "Cart", action = "RemoveRow", ms = UrlParameter.Optional });
}
}
CartController.cs
public class CartController : Controller
{
List<CartItem> listCart;
[HttpPost]
public ActionResult GetCarts()
{
listCart = Cart.getCart(Session);
return PartialView("Cart", listCart);
}
public void AddCart(string ms, string sl) {
int masach = int.Parse(ms);
int soluong = int.Parse(sl);
Cart.AddCart(masach, soluong, Session);
//return PartialView("Default");
}
public void RemoveRow(string strms)
{
int ms1 = int.Parse(strms);
var sach = new Sach() { MaSach = ms1 };
Cart.removeCart(sach, true);
}
}
Ajax js code
<script type="text/javascript">
function showCart() {
// alert("1");
//Load content from CartController
$(function () {
//alert("2");
$.ajax({
type: "POST",
url: '#Url.Action("GetCarts", "Cart")',
success: function (data) {
var result = data;
$('#myCart').html(result);
//alert($('#myCart').html());
}
});
});
$("#myCart").modal('show');
}
function addCart(ms, sl) {
var masach = [];
masach.push(ms);
masach.push(sl);
// alert(masach);
$(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("AddCart", "Cart")/'+ms+'/'+ $("#soluong").val(),
success: function (data) {
showCart();
}
});
return false;
});
}
function removeRow(strms){
$(function () {
// alert(strms);
$.ajax({
type: 'POST',
url: '#Url.Action("RemoveRow", "Cart")/' + strms,
success: function (data) {
showCart();
}
});
});
}
</script>
try passing the parameter in the data property, I have multiple examples but not at home right now.
function removeRow(this_strms){
$(function () {
// alert(strms);
$.ajax({
type: 'POST',
url: '#Url.Action("RemoveRow", "Cart")',
data: { strms: this_strms},
success: function (data) {
showCart();
}
});
});
}
I normally pass C# objects/classes as parameters like this
public void RemoveRow(CartObject strms)
{
int ms1 = strms.ms1;
var sach = new Sach() { MaSach = ms1 };
Cart.removeCart(sach, true);
}
in JS i do something like this
var thisCartObject= {
ms1: 1,
otherproperty: 0.4,
otherproperty2: "Description"
};
function removeRow(thisCartObject){
$(function () {
// alert(strms);
$.ajax({
type: 'POST',
url: '#Url.Action("RemoveRow", "Cart")',
data: JSON.stringify({ strms: thisCartObject}),
contentType: 'application/json',
dataType: 'json',
success: function (data) {
showCart();
}
});
});
}
If you are going to try this, try without! your custom route defined in the RegisterRoutes class first.
Rename the javascript variable: "strms" to "ms" and then send it, because in your route "CartRemoveRow" you will receive a variable declared with the name "ms" not "strms".
And of course, in your controller, rename the parameter in the method "RemoveRow" to "ms".
Or more short, change your route to accept "strms":
routes.MapRoute(
"CartRemoveRow",
"{controller}/{action}/{strms}",
new { controller = "Cart", action = "RemoveRow", strms = UrlParameter.Optional });
}

how to get the checkbox in edit modal popup in MVC-4

I'm using ajax to get the corresponding row values in modal popup for edit in MVC 4 razor..
for username textbox i get like this...
#Html.TextBoxFor(u => u.useredit.userName,new { #class = "input-xlarge focused", id="Edituname", type = "text" })
if i use same method for checkbox..
#Html.CheckBoxFor(u => u.useredit.isActive, new {id="EditActiv"})
i'm getting plain checkbox.where i gone wrong..or is there any other way for check box,,
Controller:
for getting values through ajax
[HttpPost]
public ActionResult getUserState(int userid)
{
TBLAppUser user = new TBLAppUser();
user = _repository.GetUserByID(userid);
string[] data = new string[10];
data[0] = user.userName;
data[1] = user.firstName;
data[2] = user.lastName;
data[3] = user.email;
data[4] = user.userID.ToString();
data[5] = user.statusID.ToString();
data[6] = user.isdelete.ToString();
data[7] = user.userName;
data[8] = user.password;
data[9] = user.isActive.ToString();
return Json(data);
}
javascript:
<script type="text/javascript">
function Getuser(_StateId) {
var url = "/admin/getUserState/";
$.ajax({
url: url,
data: { userid: _StateId },
cache: false,
type: "POST",
success: function (data) {
$('#Edituname').val(data[0]);
$('#Editfname').val(data[1]);
$('#Editlname').val(data[2]);
$('#Editemail').val(data[3]);
$('#Editid').val(data[4]);
$('#state').val(data[5]);
$('#isdelete').val(data[6]);
$('#Editname1').val(data[7]);
$('#Editpsd').val(data[8]);
$('#EditActiv').val(data[9]);
},
error: function (response) {
alert("error:" + response);
}
});
}
view.cshtml:
#Html.CheckBoxFor(u => u.useredit.isActive, new {id="EditActiv"})
i'm getting the unchecked checkbox in edit popup..pls smeone help me..thnks in advance...
For your view
#Html.CheckBoxFor(u => u.useredit.isActive, new {id="EditActiv"})
Make the below changes and see if it working
[HttpPost]
public ActionResult getUserState(int userid)
{
data[9] = user.isActive.ToString()
return Json(data);
}
Try use prop() method
<script type="text/javascript">
function Getuser(_StateId) {
var url = "/admin/getUserState/";
$.ajax({
url: url,
data: { userid: _StateId },
cache: false,
type: "POST",
success: function (data) {
var editCheck=(data[9]=== 'true')?true:false;
$('#EditActiv').prop('checked',editCheck); //use prop()
}
});

How to initialize knockoutjs view model with .ajax data

The following code works great with a hardcoded array (initialData1), however I need to use jquery .ajax (initialData) to initialize the model and when I do the model shows empty:
$(function () {
function wiTemplateInit(winame, description) {
this.WIName = winame
this.WIDescription = description
}
var initialData = new Array;
var initialData1 = [
{ WIName: "WI1", WIDescription: "WIDescription1" },
{ WIName: "WI1", WIDescription: "WIDescription1" },
{ WIName: "WI1", WIDescription: "WIDescription1" },
];
console.log('gridrows:', initialData1);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{UserKey: '10'}",
url: "WIWeb.asmx/GetTemplates",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
initialData.push(new wiTemplateInit(data.d[i].WiName,data.d[i].Description));
}
//console.log('gridrows:', initialData);
console.log('gridrows:', initialData);
}
});
var viewModel = function (iData) {
this.wiTemplates = ko.observableArray(iData);
};
ko.applyBindings(new viewModel(initialData));
});
I have been trying to work from the examples on the knockoutjs website, however most all the examples show hardcoded data being passed to the view model.
make sure your "WIWeb.asmx/GetTemplates" returns json array of objects with exact structure {WIName : '',WIDescription :''}
and try using something like this
function wiTemplateInit(winame, description)
{
var self = this;
self.WIName = winame;
self.WIDescription = description;
}
function ViewModel()
{
var self = this;
self.wiTemplates = ko.observableArray();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{UserKey: '10'}",
url: "WIWeb.asmx/GetTemplates",
success: function (data)
{
var mappedTemplates = $.map(allData, function (item) { return new wiTemplateInit(item.WiName, item.Description) });
self.wiTemplates(mappedTemplates);
}
});
}
var vm = new ViewModel();
ko.applyBindings(vm);
If you show us your browser log we can say more about your problem ( Especially post and response ). I prepared you a simple example to show how you can load data with ajax , bind template , manipulate them with actions and save it.
Hope this'll help to fix your issue : http://jsfiddle.net/gurkavcu/KbrHX/
Summary :
// This is our item model
function Item(id, name) {
this.id = ko.observable(id);
this.name = ko.observable(name);
}
// Initial Data . This will send to server and echo back us again
var data = [new Item(1, 'One'),
new Item(2, 'Two'),
new Item(3, 'Three'),
new Item(4, 'Four'),
new Item(5, 'Five')]
// This is a sub model. You can encapsulate your items in this and write actions in it
var ListModel = function() {
var self = this;
this.items = ko.observableArray();
this.remove = function(data, parent) {
self.items.remove(data);
};
this.add = function() {
self.items.push(new Item(6, "Six"));
};
this.test = function(data, e) {
console.log(data);
console.log(data.name());
};
this.save = function() {
console.log(ko.mapping.toJSON(self.items));
};
}
// Here our viewModel only contains an empty listModel
function ViewModel() {
this.listModel = new ListModel();
};
var viewModel = new ViewModel();
$(function() {
$.post("/echo/json/", {
// Data send to server and echo back
json: $.toJSON(ko.mapping.toJS(data))
}, function(data) {
// Used mapping plugin to bind server result into listModel
// I suspect that your server result may contain JSON string then
// just change your code into this
// viewModel.listModel.items = ko.mapping.fromJSON(data);
viewModel.listModel.items = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
});
})

Categories

Resources