im trying to get the values of all the checked checkboxes and post those values(integer) to an action result, the problem is i get an empty array at the controller side ...
my jquery code is as follow:
function getIds() {
var idList = new Array();
var loopCounter = 0;
//find all the checked checkboxes
$("input:checked").each
(
function() {
//fill the array with the values
idList[loopCounter] = $(this).val();
loopCounter += 1;
}
);
//Send the list off
alert(idList);
var postData = { values: idList };
$.post("/Admin/Delete/", postData);
}
my controller side code is following
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Delete(Int32[] values)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("NewSubDashboard");
}
catch
{
return View();
}
}
there is no problem with the posting but im gettin an empty array at the controller side...
Shouldn't your $.post be:
$.post("/Admin/Delete/", postData);
Since postData:idList is probably undefined.
i extracted the values from httpcontext as
HttpContext ctx = System.Web.HttpContext.Current;
string[] ValArr = ctx.Request.Params.GetValues(0);
Related
So, i call trhough Ajax an IActionResult to go to another view and the IActionResult executes entirely except that it doesn't return the view.
Here is the code of the action result, it just take some products and search for their prices on the database and then sums them. And it executes perfectly. I changed the code a little to some lines to show me the values of each variable in the console and it works fine. The only problem is that when it suppose to show the view in the browser, nothing happens
[HttpPost]
public IActionResult Cart(List<int[]> carrito){
var productsToBuy = selectProductsByID(carrito);
var detallesOrden = new List<OrderDetailModel>();
int sumaTotal = 0;
for(int i = 0; i<carrito.Count; i++){
var detalle = new OrderDetailModel{
idProduct = carrito[i][0],
cantidad = carrito[i][1],
subTotal = productsToBuy[i].precio * carrito[i][1]
};
sumaTotal += detalle.subTotal;
}
var orden = new OrderModel{
estado = 0,
sumaTotal = sumaTotal
};
ViewBag.ProductsToBuy = productsToBuy;
ViewBag.DetallesOrden = detallesOrden;
ViewBag.Orden = orden;
return View();
}
This is the function which i use to call the actionresult it sends an array with the products id and their quantities
function goToCart(){
showCart();
var target = '#Url.Action("Cart", "Home")';
$.ajax({
type: 'POST',
data:{
carrito: carrito
},
url: target,
success: function(result){
},
error: function(result){
alert('error');
}
});
}
What am i doing wrong? I'll appreciate any kind of help.
Sorry for the combinnation of english and spanish.
Im trying to save to a table in this format -
I get the data as an array of ints for EmbellishmentPositionID in a viewmodel from checkbox values, i want to save them to the DB (SQL) as in the table. The EmbellishmentProductTypeID i get from the VM also.
This is all in MVC C#
Can someone help me out please? Ive tried -
[HttpPost]
public ActionResult Edit(ProductTypeVM viewModel)
{
try
{
if (viewModel == null)
throw new ArgumentNullException(nameof(viewModel));
if (ModelState.IsValid)
{
var dataModel = _epdRepository.Table.Where(x => x.EmbellishmentProductTypeID == viewModel.Id);
_epdRepository.Delete(dataModel);
var model = new EmbellishmentProductDetailRecord();
model.EmbellishmentProductTypeID = viewModel.Id;
_epdRepository.Insert(model);
}
else
{
throw new ArgumentNullException(nameof(viewModel));
}
}
catch (Exception ex)
{
throw;
}
return View();
}
Array picture -
This is a sample. Hope to help, my friend :))
foreach(var item in viewModel.Values) //loop all array data
{
var model = new EmbellishmentProductDetailRecord();
model.EmbellishmentProductTypeID = viewModel.Id;
model.EmbellishmentPositionID = item;
model.EmbellishmentID = ??? //I dont know which value to bind
_epdRepository.Insert(model);
}
This is my first time using JSON and I'm having a bit of trouble parsing and using it in my controller. I already tried these solutions Unable to successfully receive JSON data to .NET MVC Controller, How to receive JSON as an MVC 5 action method parameter, but none of them made it for me.
I'm retrieving some data from my html and sending the arrays through ajax to the controller in the following code:
JQuery:
var values = $('ul#values li').map(function() {
return this.textContent;
}).get()
var lines = $('ul#lines li').map(function() {
return {
Column: this.textContent,
Table: this.getAttribute("name")
};
}).get();
var columns = $('ul#lines li').map(function() {
return {
Column: this.textContent,
Table: this.getAttribute("name")
};
}).get();
var filters = $('ul#filters li.panel').map(function () {
var n = this.getAttribute("name");
var c = $(this).children()[1].textContent;
var r = $(this).find("li input:checked").map(function() {
return this.parentNode.textContent;
}).get();
if (r.length === 0)
return null;
else
return { table: n, name:c, vals: r };
}).get();
$.ajax({
type: "POST",
url: "/Home/PivotTable",
dataType: "json",
traditional: true,
data: {
indicators: values,
lines: JSON.stringify(lines) ,
columns: JSON.stringify(columns),
filters: JSON.stringify(filters)
},
success: function (data) {
alert(data.s, data.l);
}
});
And this is the form data being posted:
indicators: Taxa Mensal de inflação
lines:[{"Column":" Base","Table":"D_Base"}]
columns:[{"col":" Trimestre","table":"D_Calendario"}]
filters:[{"table":"D_PF_ClasseProdutos","name":" Código","vals":[" 22"," 23"]}]
And receiving the data in the controller where I need to access the data:
public JsonResult PivotTable(string[] indicators, Lines[] lines, object[] columns, object[] filters)
{
string sa = indicators[0];
var l = lines;
var col = columns;
var fil = filters;
var result = new { s = sa, l=l[0].Column};
return Json(result, JsonRequestBehavior.AllowGet);
}
public class Lines
{
public string Column { get; set; }
public string Table { get; set; }
}
I tried binding lines to an object, like the solution in one of the links, but got
NullRefrenceException was unhandled by usercode
While the other parameters receive the appropriate
data, but i can´t access the properties of the object.
What am I doing wrong, and how can i parse the data or bind it to an object?
You can try to use Json.NET library which allows you to serialize and deserialize.
Pass your params as string and do the following:
Lines[] m = JsonConvert.DeserializeObject<Lines>(lines);
I want to update array in my mongoDB collection. Posting new document works just fine, but it won't update array. Structure of my document is:
var document = new BsonDocument
{
{ "post_title", model.Title },
{ "post_text", model.Text },
{ "post_author", model.Author },
{ "post_picture", model.Picture },
{ "post_comments", new BsonArray() },
};
And my update function is:
[HttpPost]
[Route("api/PostInfo/{Comment}")]
public async Task Post(Comment comment)
{
try {
BsonObjectId oldId = new BsonObjectId(new ObjectId(comment.id.ToString()));
var mongoDbClient = new MongoClient("mongodb://127.0.0.1:27017");
var mongoDbServer = mongoDbClient.GetDatabase("nmbp");
var collection = mongoDbServer.GetCollection<PostInfo>("post");
var filter = Builders<PostInfo>.Filter.Eq(e => e._id, oldId);
var update = Builders<PostInfo>.Update.Push("post_comments", comment.comment);
await collection.FindOneAndUpdateAsync(filter, update);
var test = oldId.GetType();
}
catch
{
}
}
When debugging, i can see that post controller is triggered, and comment values are correct, but when I take a look in database, value of "post_comments" array is empty. No error is thrown in catch block. Am I doing something wrong?
It looks like the problem was in this line:
var filter = Builders<PostInfo>.Filter.Eq(e => e._id, oldId);
The correct one should look like this:
var filter = Builders<PostInfo>.Filter.Eq("_id", oldId);
I have to refresh the items of two ListBox after a dropdownlist value change.
The data of the ListBoxes is in the ViewData and i call a action controller from jquery function, but the ViewData after the call have the same data.
Here is the code:
$(document).ready( function () {
$('#users').change(function () {
var selectedValue = $('#users').val();
$.post('#Url.Action("GruposUsuario", "Grupos")', { usersId: selectedValue }, function () {
var gruposAsig = JSON.parse('#Html.Raw(Json.Encode(ViewData["gruposAsignados"]))');
var gruposDisp = JSON.parse('#Html.Raw(Json.Encode(ViewData["gruposDisponibles"]))');
$('#gruposAsignados').empty();
$('#gruposAsignados').addItems(gruposAsig);
$('#gruposDisponibles').empty();
$('#gruposDisponibles').addItems(gruposDisp);
});
});
$.fn.addItems = function (grupos) {
return this.each(function () {
var list = this;
$.each(grupos, function (index, itemData) {
var option = new Option(itemData.Text, itemData.Value);
list.add(option);
});
});
};
});
And the Controller Code:
[HttpPost]
public ActionResult GruposUsuario(string usersId)
{
AllUsers();
GruposAsignados(int.Parse(usersId));
//GruposDispobibles(int.Parse(usersId));
return Json("Usuario");
}
void GruposAsignados(int usersId)
{
var grupos = new BL.Grupos().GruposAsignados(usersId);
List<SelectListItem> list = new List<SelectListItem>();
foreach (var grupo in grupos)
{
SelectListItem selectList = new SelectListItem()
{
Text = grupo.GroupName,
Value = grupo.GroupsId.ToString()
};
list.Add(selectList);
}
ViewData["gruposAsignados"] = list as IEnumerable<SelectListItem>;
}
How can i refesh the ViewDatas after the event?
Razor code is parsed on the server before it is sent to the view. Your use of #Html.Raw(...) assigns vales to gruposAsig and gruposDisp that are the initial values of the ViewData properties (inspect the source when you first render the page).
In any case you method GruposAsignados() only returns a string with the value "Usuario". If you want to return json data to update the options in two dropdownlists, then you controller method should be
[HttpGet] // its a GET
public ActionResult GruposUsuario(string usersId)
{
var gruposAsignados= new BL.Grupos().GruposAsignados(usersId).Select(g => new
{
ID = g.grupo.GroupsId;
Name = g.GroupName;
}
var gruposDisponibles = // another query
return Json(new { Asignados = gruposAsignados, Disponibles = gruposDisponibles, JsonRequestBehavior.AllowGet);
}
Then the script should be
var asignados = $('#gruposAsignados'); // cache it
var disponibles = $('#gruposDisponibles');
$.getJSON('#Url.Action("GruposUsuario", "Grupos")', { usersId: selectedValue }, function (response) {
if(response) {
asignados.empty();
// or asignados.empty().append($('</option>').val('').text('-Please select-'));
$.each(response.Asignados, function(index, item) {
asignados.append($('</option>').val(item.ID).text(item.Name));
});
disponibles.empty();
$.each(response.Disponibles, function(index, item) {
disponibles.append($('</option>').val(item.ID).text(item.Name));
});
}
});
Side note: There is no need to create IEnumerable<SelectListItem>. The browser has no knowledge of what a C# class is and you just returning extra unnecessary data (the values of the Selected, Group and Disabled properties) which are never used.