Can not save a list to a session/ViewBag variable - c#

I have an MVC action where I get some data from the UI. Now, I want to assign those data to an object, and then save that object in a session list. But, with every request, the count of the session is 0.
[HttpPost]
public ActionResult AddToCart(Purchase purchase)
{
if(Session["AddedProduct"] == null)
{
List<AddedProductView> addedProducts = new List<AddedProductView>();
AddedProductView addedProductView = new AddedProductView();
addedProductView.ProductId = purchase.ProductId;
addedProducts.Add(addedProductView);
Session["AddedProduct"] = addedProducts;
}
else
{
List<AddedProductView> addedProducts = (List<AddedProductView>)Session["AddedProduct"];
AddedProductView addedProductView = new AddedProductView();
addedProductView.ProductId = purchase.ProductId;
addedProducts.Add(addedProductView);
Session["AddedProduct"] = addedProducts;
}
return View();
}
Here, with every request, I end up with a new list, which means every time executes the if condition. I have serialized in my class. What am I doing wrong here?
And, my script is like:
<script>
$(document).ready(function () {
$('#btnAddToCart').click(function () {
var data = $('#PurchaseForm').serialize();
$.ajax({
type: 'Post',
url: '/Purchase/AddToCart',
data: data,
success: function (response) {
window.location = '/Purchase/AddToCart'
}
})
})
})
</script>

Try the below:
HttpContext.Current.Session.Add("currentUser", appUser);
And,
HttpContext.Current.Session["currentUser"]

just needed to return json() instead of empty view().

Related

Update C# variable via Ajax?

I have got a page full of posts, I sort those posts before rendering it.
Now I have created a drop down so user's can sort the posts by newest or oldest.
The only problem is I don't know how to update the server-side variable through Ajax.
#{
var SortSelected = "";
var sortedArticles = ListOfPosts.OrderBy(x => x.GetPropertyValue<DateTime>("articleDate")).Reverse().ToList();
if (SortSelected == "Most recent")
{
sortedArticles = ListOfPosts.OrderBy(x => x.GetPropertyValue<DateTime>("articleDate")).Reverse().ToList();
}
else if (SortSelected == "Oldest")
{
sortedArticles = ListOfPosts.OrderBy(x => x.GetPropertyValue<DateTime>("articleDate")).ToList();
}
}
I have removed other code which is irrelevant to make it cleaner.
That's my code for the posts, this is the Razor(html)
<div class="AnimatedLabel">
<select name="contact" class="tm-md-12">
<option id="hide-selector-dropdown" value=""></option>
#foreach (var item in FilterTypes)
{
<option value="#item">#item</option>
}
</select>
<label for="contact">Sort by</label>
<span class="tm-icon-arrow--right" id="selector-dropdown-arrow"></span>
</div>
This is how I tried to do it -
<script>
$('select').on('change', function () {
SortSelected = this.value;
});
</script>
But it is not updating the value, I have been told because it is server-side.
I know people will probably roast me for this question but I do not know any other solution so any help would be great!
I do not have much experience with .net/c#
Thanks!
Okay, so I just wanted to show you how you can achieve something like this using AJAX. As far as I have understood, you want to sort your posts list based on the selection from the user in the dropdown list that you have. Please refer to the code snippet below and let me know if you were able to get what you wanted regarding your requirement:
<script>
$('select').on('change', function () {
//SortSelected = this.value;
//First get the text of the selected item
var selectedText=$('#hide-selector-dropdown :selected').text();
//Now generate your JSON data here to be sent to the server
var json = {
selectedText: selectedText
};
//Send the JSON data via AJAX to your Controller method
$.ajax({
url: '#Url.Action("ProcessMyValue", "Home")',
type: 'post',
dataType: "json",
data: { "json": JSON.stringify(json)},
success: function (result) {
//Show your list here
if (data.success) {
console.log(data.sortedArticles);
}
else {
console.log("List empty or not found");
}
},
error: function (error) {
console.log(error)
}
});
});
</script>
Your Controller would look like:
using System.Web.Script.Serialization;
[HttpPost]
public ActionResult ProcessMyValue(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
var SortSelected= jsondata["selectedText"];
//Do something with your variables here. I am assuming this:
var sortedArticles = ListOfPosts.OrderBy(x => x.GetPropertyValue<DateTime>("articleDate")).Reverse().ToList();
if (SortSelected == "Most recent")
{
sortedArticles = ListOfPosts.OrderBy(x => x.GetPropertyValue<DateTime>("articleDate")).Reverse().ToList();
}
else if (SortSelected == "Oldest")
{
sortedArticles = ListOfPosts.OrderBy(x => x.GetPropertyValue<DateTime>("articleDate")).ToList();
}
return Json(new { success = true, sortedArticles }, JsonRequestBehavior.AllowGet);
}
You can't change server variable value but you can use this for refresh your table.
<script>
$('select').on('change', function () {
$.get('/Url' , {sortBy:this.value}).done(function(result){
$('#yourTable').html(result);
}).fail(function(){
alert('Error !');
});
});
</script>
You can call web method in server side using ajax.
Use that method to update variable on server side

Posting AJAX string to MVC Controller

I am trying to post a string (the name of the href the user clicked on) using AJAX to my MVC controller (which it will then use to filter my table results according to the string).
Whilst I have managed to get it to post (at-least according to the alerts) on the AJAX side, it doesn't seem to arrive properly on the controller side and is seen as null in my quick error capture (the if statement).
Please excuse the useless naming conventions for the moment. I've been going through countless methods to try and fix this, so will name properly when I've got a proper solution :).
I've been at work for this for a long while now and can't seem to solve the conundrum so any help is appreciated please! I'm very new to AJAX and MVC in general so I'm hoping it's a minor mistake. :) (FYI I have tried both post and get and both seem to yield the same result?)
Controller:
[Authorize]
[HttpGet]
public ActionResult GetSafeItems(string yarp)
{
using (CBREntities2 dc = new CBREntities2())
{
if (yarp == null)
{
ViewBag.safeselected = yarp;
}
var safeItem = dc.Items.Where(a => a.Safe_ID == yarp).Select(s => new {
Serial_Number = s.Serial_Number,
Safe_ID = s.Safe_ID,
Date_of_Entry = s.Date_of_Entry,
Title_subject = s.Title_subject,
Document_Type = s.Document_Type,
Sender_of_Originator = s.Sender_of_Originator,
Reference_Number = s.Reference_Number,
Protective_Marking = s.Protective_Marking,
Number_recieved_produced = s.Number_recieved_produced,
copy_number = s.copy_number,
Status = s.Status,
Same_day_Loan = s.Same_day_Loan
}).ToList();
// var safeItems = dc.Items.Where(a => a.Safe_ID).Select(s => new { Safe_ID = s.Safe_ID, Department_ID = s.Department_ID, User_ID = s.User_ID }).ToList();
return Json(new { data = safeItem }, JsonRequestBehavior.AllowGet);
}
}
AJAX function (on View page):
$('.tablecontainer').on('click', 'a.safeLink', function (e) {
e.preventDefault();
var yarp = $(this).attr('safesel');
var selectedSafeZZ = JSON.stringify("SEC-1000");
$.ajax({
url: '/Home/GetSafeItems',
data: { 'yarp': JSON.stringify(yarp) },
type: "GET",
success: function (data) {
alert(yarp);
console.log("We WIN " + data)
},
error: function (xhr) {
alert("Boohooo");
}
});
})
** The Alert reveals the correct type: "SEC-1000"
But the console Log shows: WE WIN [Object object]??
I have tried something basic in a new mvc dummy project :
View page basic textbox and a button :
<input type="text" id="txt_test" value="test"/>
<button type="button" class="btn" onclick="test()">Test</button>
<script type="text/javascript">
function test()
{
var text = $("#txt_test")[0].value;
$.ajax({
url: '#Url.RouteUrl(new{ action="GetSafeItems", controller="Home"})',
// edit
// data: {yarp: JSON.stringify(text)},
data: {yarp: text},
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(data) {
// edit
// alert(JSON.stringify(data));
alert(data.data);
}});
}
</script>
Controller :
[HttpGet]
public ActionResult GetSafeItems(string yarp)
{
return Json(new {data = string.Format("Back end return : {0}",yarp)}
, JsonRequestBehavior.AllowGet);
}
Alert result => {"data":"Back end return : \"test\""}
It's a simple ajax call to a web method. You don't return a view, so I don't understand the use of
if (yarp == null)
{
ViewBag.safeselected = yarp;
}
Also I see an [Authorize] attribute, you perhaps use some authentication and I don't see any authentication header on your ajax call
Try this:
$.each(data, function (i) { console.log("We WIN " + data[i].Serial_Number )});

Cant do redirect (ASP.NET MVC)

I need to do redirect to controller
Here is my controller
[HttpPost]
public ActionResult Index(string question1, string question2, string question3, string question4, string question5, string question6, string question7, string question8, string question9, string question10, Int32 id)
{
QuestionBlock question = new QuestionBlock
{
Question1 = question1,
Question2 = question2,
Question3 = question3,
Question4 = question4,
Question5 = question5,
Question6 = question6,
Question7 = question7,
Question8 = question8,
Question9 = question9,
Question10 = question10,
Interview_Id = id,
};
//TempData["id"] = id;
db.QuestionBlocks.Add(question);
db.SaveChanges();
return Json(new { Result = "Success", Message = "Saved Successfully" }, JsonRequestBehavior.AllowGet);
I try to do it like this
return RedirectToAction("Index", "Questions", new { id = id });
I have this AJAX call in my View. Maybe trouble in it?
<script>
$('.click').on('click', function () {
$('.content').toggle();
});
var counter = 0;
$(document).ready(function () {
$('#save').click(function () {
save();
});
});
function save()
{
$.ajax({
type: 'Post',
dataType: 'Json',
data: {
question1: $('#Question1').val(),
question2: $('#Question2').val(),
question3: $('#Question3').val(),
question4: $('#Question4').val(),
question5: $('#Question5').val(),
question6: $('#Question6').val(),
question7: $('#Question7').val(),
question8: $('#Question8').val(),
question9: $('#Question9').val(),
question10: $('#Question10').val(),
},
url: '#Url.Action("Index", "Questions")',
success: function (da) {
if (da.Result === "Success") {
alert('Вопросы сохранены');
} else {
alert( 'Error'+ da.Message);
}
},
error: function (da) {
alert('Error');
}
});
}
</script>
But redirection not works. Where is my trouble?
Maybe I need to do it not in controller?
Thank's for help
Your current code is returning a JSON response with 2 properties and your main view code is making an ajax call to this action method. So the JSON response returned from the action method will be handled in the success handler of your ajax call. It will not do a redirect unless you explicitly do so.
Even if you replace the return Json with return RedirectToAction, It does not makes sense to use it with the Ajax call. The whole idea of ajaxifying the page is to avoid the traditional page submit - reload experience and replace it with partial page upload behavior (better user experience)
If you absolutely want to redirect to another page, you can do that in the success event handler. But like i mentioned earlier, it does not makes sense to do an ajax post then. Do a normal form post!
if (da.Result === "Success") {
window.location.href="Give the new Url you want to navigate to here";
}
You can use the UrlHelper class to generate the correct url to the other action method and send that as part of your JSON response.
var urlBuilder = new UrlHelper(Request.RequestContext);
var url = urlBuilder.Action("Index", "Questions",new { id= id});
return Json(new { Result = "Success", Message = "Saved Successfully",RedirectUrl=url });
Now in your ajax call , read the RedirectUrl property
if (da.Result === "Success") {
window.location.href=da.RedirectUrl;
}
Have you tried just like this without writing Questions.:
return RedirectToAction("Index", new { id = yourvalue });
EDIT:
Otherwise you can try this:
return RedirectToAction( "Index", new RouteValueDictionary(
new { controller = controllerName, action = "Index", id = id } ) );

mvc ajax refresh div method controller json

I have a method in the controller that return a ViewBag with Json.
public JsonResult FilterCheck(int id, int[] mycheck, string idprot)
{
ViewBag.Utenti = this.GetDbContext().utente.Include(s => s.cod_servizio_utente).Where(x => x.cod_servizio_utente.Select(l => l.id).Contains(5)).ToList();
return Json(ViewBag.Utenti, JsonRequestBehavior.AllowGet);
}
In the view I have this script function ajax, if this function have "success" i would refresh a div that include a foreach on the viebag.Utenti:
$.ajax({
type: "POST",
url: "#Url.Action("FilterCheck","Operatore")",
datatype: "json",
traditional: true,
data: { 'mycheck': mycheck, 'idprot': idprot, 'id': '#Model.id' },
success: function(data) {
var html = $(data).filter('#external-events').html();
$('#external-events').html(data);
}
});
<div id='external-events'>
#foreach (HAnnoZero.Repositories.utente item in ViewBag.Utenti)
{
<div class='col-lg-3'><div class='external-event'>#item.id- #item.cognome #item.nome</div></div>
} </div>
But dont work. How can do for refresh the foreach inside div id "external events"?Who could help me?
Firstly you do not need to assign the collection to ViewBag
public ActionResult FilterCheck(int id, int[] mycheck, string idprot)
{
var data = this.GetDbContext().utente.Include(......
// Build anonymous object collection to avoid circular reference errors
var response = data.Select(d => new
{
id = d.id,
cognome = d.cognome
// other properties as required
});
return Json(response);
}
Secondly you are returning JSON, not html, so in your success function you need to iterate through the properties and build your html (not sure what your properties are, so adjust as necessary)
success: function(data) {
$('#external-events').empty(); // clear existing items
$.each(data, function(index, item) {
var div = $('<div><div>'); // Create new element
div.text(item.id + ' ' + item.cognome); // Set inner text
$('#external-events').append(div); // add the new element
});
}
An alternative is to have the action method return a partial view containing the html and then use
success: function(data) {
$('#external-events').html(data);
}

How to retrive json result values in javascript?

I have a javascript function which redirects to given url after i had a json result.I want this json result values in my html inputs on success.Please help me i am new to MVC
function GetSupplierDetail(SupId) {
var url = "/PurchaseOrders/GetSupplierDetails/";
$.ajax({
url: url,
data: { SuppId: SupId },
cache: false,
type: "POST",
success: function (data) {
alert(data.modelList);
},
error: function (reponse) {
}
});
}
This is my C# Action.
[HttpPost]
public ActionResult GetSupplierDetails(int SuppId)
{ var books = entity.P_Supplier.Where(x => x.SupplierId == SuppId).ToList();
var modelList = books.Select(x => new SupplierModel()
{
Firm = x.Firm,
Sname = x.Sname,
SupplierName=x.SupplierName,
Address1=x.Address1,
Cell=x.Cell,
Email=x.Email,
Fax=x.Fax
});
return Json(modelList,JsonRequestBehavior.AllowGet);
alert(data.modelList); returns object which contains a collection.You need to loop over that collection.If you want to bind collection with GridView then there are different open source grids are available i.e Backgrid,flexigrid.
If there is just single result then you can check it by alert(data.modelList.Firm);
or assign it to any input fields.
$('#txtFirm').val(data.modelList.Firm);

Categories