I am implementing "show more posts" in my blogs list following
this example but I want to make a change and switch from using ViewData to ViewModel.
This the relevant code:
private void AddMoreUrlToViewData(int entryCount)
{
ViewData["ShowMore "] = Url.Action("Index", "Messaggi", new { entryCount = entryCount + defaultEntryCount });
}
that I switch to
ViewModel.ShowMore = Url.Action("Index", "Messaggi", new { entryCount = entryCount + defaultEntryCount });
the Index action of the example:
public ActionResult Index(int? entryCount)
{
if (!entryCount.HasValue)
entryCount = defaultEntryCount;
int totalItems;
if(Request.IsAjaxRequest())
{
int page = entryCount.Value / defaultEntryCount;
//Retrieve the page specified by the page variable with a page size o defaultEntryCount
IEnumerable<Entry> pagedEntries = GetLatestEntries(page, defaultEntryCount, out totalItems);
if(entryCount < totalItems)
AddMoreUrlToViewData(entryCount.Value);
return View("EntryTeaserList", pagedEntries);
}
//Retrieve the first page with a page size of entryCount
IEnumerable<Entry> entries = GetLatestEntries(1, entryCount.Value, out totalItems);
if (entryCount < totalItems)
AddMoreUrlToViewData(entryCount.Value);
return View(entries);
}
Here I add a lot of code to load the post from the db, the only code I think is relevant is that I swtich return View("EntryTeaserList", pagedEntries); to return View(myViewModel); after setting BlogsList and ShowMore property.
But my problem is in the javascript command:
$(function() {
addMoreLinkBehaviour();
});
function addMoreLinkBehaviour() {
$('#entryTeaserList #moreLink').live("click", function() {
$(this).html("<img src='/images/ajax-loader.gif' />");
$.get($(this).attr("href"), function(response) {
$('#entryTeaserList ol').append($("ol", response).html());
$('#entryTeaserList #ShowMore').replaceWith($("#ShowMore", response));
});
return false;
});
}
where
$('#entryTeaserList #ShowMore').replaceWith($("#ShowMore", response));
to take ViewData property and use it to replace the link.
How can I read the ViewModel Property instead?
Related
I am sort of lost on the coding part of this problem. I have a MVC application, and I am trying to populate a queries Where clause as the selected value from my drop down list. Also, I am populating the drop down list from a query in the database. For example:
SELECT db.ID FROM Database db where ID = 1232
Instead of that, I want to do something like this...
SELECT db.ID FROM Database db where ID = "SelectedValue from Dropdownlist"
Model Class:
public string ID {get; set;}
public string Summary{get; set;}
public int Estimate {get; set;}
public List<Hello> getIDs()
{
var que = (from wre in db.Table
select new Hello{
ID = wre.ID
}).toList();
}
Controller class:
public ActionResult Index(string? IDParam)
{
var model = test.getStuff();
var que = (from wre in db.View
where wre.ID == IDParam //Operator '==' cannot be applied to operands of type 'string' and 'string?'
select new Hello
{
ID = wre.ID
Summary = wre.Summary,
Estimate = wre.Estimate
}).toList();
if (IDParam!= null & IDParam.HasValue)
{
model = model.Where(x => x.ID == IDParam); //Operator '==' cannot be applied to operands of type 'string' and 'string?'
}
return View(model);
}
View Class:
#Html.DropDownList("ID", ViewBag.Releases as SelectList, "ID", new {#id="rel" })
<table>
<th>#Html.DisplayNameFor(model => model.ID)</th>
<th>#Html.DisplayNameFor(model => model.Summary)</th>
<th>#Html.DisplayNameFor(model => model.Estimate)</th>
</table>
<script>
$("#rel").change(function () {
var selectedId = this.val();
location.href = '#Url.Action("Index", "SampleController", new {selectedId="_selectedId"})'.Replace("_selectedId",selectedId);
});
</script>
This works perfectly fine, but now, I am lost on the coding aspect of it. I can see the alert every time I change the ID from the drop down list. However, there is no change in the data being displayed (I know I am missing a lot). If anyone can help me out here, that would be great, thank you!
1) Try adding where clause in Linq
where wre.ID == IDParam
2) Change que to instance of your class and get firstOrDefault instead of List
3) Try passing instance of your class as a model in view
return View(test);
1- You need to get changed Id as below :
$("#rel").change(function () {
// alert("Changed");
var selectedId =this.value;
});
2- If you want to reload your page then you need to set a parametre to your [HttpGet] Method :
public ActionResult Index(int? selectedId) // selectedId
{
var que = (from wre in db.View
select new Hello
{
ID = IDParam
Summary = wre.Summary,
Estimate = wre.Estimate
}).toList();
ViewBag.Releases = new SelectList(test.getIDs(), "", "ID");
var model = test.getStuff();
if(selectedId!=null && selectedId.HasValue)
{
// do some stuff with your selectedId
// if working method is test.getStuff(), then maybe you can use like code below:
model = model.Where(x=> x.Id==selectedId);
}
return View(model);
}
and in your View:
$("#rel").change(function () {
// alert("Changed");
var selectedId =this.value;
location.href = '#Url.Action("Index", "YourController", new {selectedId="_selectedId"})'.Replace("_selectedId",selectedId);
});
3- If you dont want to reload page then you need to use Ajaxrequest, You must create a new method for get data by selectedId,
// Your view.
$("#rel").change(function () {
// alert("Changed");
var selectedId =this.value;
$.ajax({
method: "POST",
url: "'#Url.Action("GetDataBySelectedId","YourController")'",
data: { selectedId: selectedId }
})
.done(function( data) {
// Delete your table, and fill table with your data with jquery.
});
});
// your Controller:
[HttpPost]
public JsonResult GetDataBySelectedId(int? selectedId)
{
// Do some stuff for get your data.
var data = yourData.Where(x=> x.Id = selectedId.Value);
return Json(data);
}
I'm developing an asp.net mvc 5 online store project . I want to create cart to add Goods with Cookie . I'm confused about it and don't know why it didn't work . it didn't gave me any error . also I add break points to debug it but any data didn't send to my actions !
could anyone help me ? what's the problem ?
I'm not good in javascript and I think problem would be in javascript codes :/
Thanks in advance
Goods controller
[HttpPost]
public ActionResult AddToCart(int Id, int Count)
{
try
{
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
//edit cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), (Convert.ToInt32(Request.Cookies["NishtmanCart_" + Id.ToString()].Value) + 1).ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Set(cookie);
}
else
{
//add new cookie
var cookie = new HttpCookie("NishtmanCart_" + Id.ToString(), Count.ToString());
cookie.Expires = DateTime.Now.AddMonths(1);
cookie.HttpOnly = true;
Response.Cookies.Add(cookie);
}
int CartCount = Request.Cookies.AllKeys.Where(p => p.StartsWith("NishtmanCart_")).Count();
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("product added to your basket", MessageType.Success).Script,
Html = "Shopping Cart (" + CartCount.ToString() + ")"
});
}
catch (Exception)
{
return Json(new MyJsonData()
{
Success = false,
Script = MessageBox.Show("product didn't add to your basket", MessageType.Error).Script,
Html = ""
});
}
}
public ActionResult RemoveCart(int Id)
{
try
{
int CartCount = Request.Cookies.AllKeys.Where(p => p.StartsWith("NishtmanCart_")).Count();
if (Request.Cookies.AllKeys.Contains("NishtmanCart_" + Id.ToString()))
{
Request.Cookies["NishtmanCart_" + Id.ToString()].Expires = DateTime.Now.AddDays(-1);
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("product removed from your basket", MessageType.Success).Script,
Html = "Shopping Cart (" + CartCount.ToString() + ")"
});
}
else
{
return Json(new MyJsonData()
{
Success = false,
Script = MessageBox.Show("this product doesn't have in your basket", MessageType.Warning).Script,
Html = "Shopping Cart (" + CartCount.ToString() + ")"
});
}
}
catch (Exception)
{
return Json(new MyJsonData()
{
Success = true,
Script = MessageBox.Show("product didn't remove from your basket", MessageType.Error).Script,
Html = ""
});
}
}
MyJsonData.cs
public class MyJsonData
{
public string Script { get; set; }
public string Html { get; set; }
public bool Success { get; set; }
}
_GoodDetailsAjax.cshtml
#foreach (var item in Model.GoodDetails)
{
<div>
<p class="nowprice">NowPrice : #item.DetailsNowPrice</p>
<p class="preprice">PrePrice : #item.DetailsPrePrice</p>
<a class="button icon-cart" href="#" GoodID="#item.DetailsGoodID">Add to cart</a><br>
<a class="link" >Shopping Cart (0)</a>
</div>
}
#section scripts{
<script src="~/Scripts/jquery-2.1.4.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script>
$(function () {
$("a.button.icon-cart").click(function (e) {
e.preventDefault();
var goodId = $(this).attr("GoodID");
alert(goodId); //////// I just added this code
$.ajax({
url: "/Goods/AddToCart",
data: { Id: goodId, Count: 1 },
type: "Post",
dataType: "Json",
success: function (result) {
if (result.Success) {
$("#CartItems").html(result.Html);
}
eval(result.Script);
},
error: function () {
alert("Error!");
}
});
});
});
</script>
}
I don't know what's the implementation of MessageBox.Show("....", MessageType.Error).Script but I'm assuming that it just generates a simple JavaScript statement like this:
Script = "alert('product added to your basket');"
So you can add this tag for the result:
<div id="CartItems">
</div>
Now it works without any problem.
All of my codes was true , I just made some simple mistakes .
I loaded a JQuery file in my layout and also I loaded another version of JQuery in my view! I deleted one of them .
And also I used those codes in a partial view and loaded they using Ajax but my partial view couldn't pass data to Controller , I moved codes to main view (GoodDetails.cshtml) and it works fine now .
I have a jquery editable table.
In code behind there are three actions.
One to load data for datatable
Another to delete data from datatable
And the last one for Save data.
There is nothing special in these actions.
I have The problem with save data. Data are saved correctly to database and then there is redirection to load data to datable again.
When data are saved correctly do database, there is redirection which load new data to datatable and then i get this warning:
DataTables warning: table id=myDataTable - Requested unknown parameter '0' for row 8. For more information about this error, please see http://datatables.net/tn/4
I have looked this error on that page and i can not still find solution for this bug.
Interesting is when i get this error and i refresh page with datatable this time data are loaded correctly.
I do not know what is going on.
Please help
Here are two problematic actions
[HttpGet]
public ActionResult TesotwanieTabelki(int promotionId)
{
marketPromocji.Areas.DELIVER.Models.PromotionsProductsViewModel promotionProductsViewModelItem =
new marketPromocji.Areas.DELIVER.Models.PromotionsProductsViewModel();
promotionProductsViewModelItem.productDetails =
new List<marketPromocji.Areas.DELIVER.Models.ProductDetails>();
marketPromocji.Models.promocje promocje = unitOfWork.PromocjeRepository.GetByID(promotionId);
aspnet_Users produktyWDanejPromocji=promocje.promocje_produkty.Select(x => x.produkty).First().aspnet_Users; //czyje produkty w danej promocji
ICollection<produkty> produkty = unitOfWork.ProduktyRepository.Get().Where(x => x.aspnet_Users.UserId== produktyWDanejPromocji.UserId).ToList();
List<SelectListItem> selectList=new List<SelectListItem>();
foreach (produkty p in produkty)
{
selectList.Add(new SelectListItem { Text = p.nazwa, Value = p.id.ToString()});
}
promotionProductsViewModelItem.selectList = selectList;
promotionProductsViewModelItem.data_start = promocje.data_start;
promotionProductsViewModelItem.data_koniec = promocje.data_koniec;
promotionProductsViewModelItem.czy_zielony_koszyk = promocje.czy_zielony_koszyk;
promotionProductsViewModelItem.id = promocje.id;
promotionProductsViewModelItem.poziom_dostepnosci = promocje.poziom_dostepnosci;
promotionProductsViewModelItem.wynagrodzenie = promocje.wynagrodzenie;
if (promocje.sposob_wynagrodzenia != null)
{
promotionProductsViewModelItem.sposobWynagrodzenia = promocje.sposob_wynagrodzenia;
}
else
{
promotionProductsViewModelItem.sposobWynagrodzenia = "";
}
ICollection<marketPromocji.Models.promocje_produkty> promocje_produkty = unitOfWork.PromocjeProduktyRepository.Get().Where(x => x.ref_promocja == promotionId).ToList();
foreach (marketPromocji.Models.promocje_produkty item in promocje_produkty)
{
promotionProductsViewModelItem.productDetails.Add(new marketPromocji.Areas.DELIVER.Models.ProductDetails()
{
productId = item.produkty.id,
cena_brutto = item.cena_brutto,
cena_brutto_dla_sklepu = item.cena_brutto_dla_sklepu,
cena_netto = item.cena_netto,
cena_netto_dla_sklepu = item.cena_netto_dla_sklepu,
nazwa = item.produkty.nazwa,
url_obrazka = item.produkty.url_obrazka
});
}
Session[User.Identity.Name] = promotionProductsViewModelItem; //this session is used for datatable update action
return View(promotionProductsViewModelItem);
}
[HttpPost]
public ActionResult AddData(FormCollection formCollection)
{
int promotionId = Convert.ToInt32(formCollection.Get("promotionId"));
string addedProductId = formCollection.Get("Produkty");
int productId = Convert.ToInt32(addedProductId);
marketPromocji.Areas.DELIVER.Models.PromotionsProductsViewModel promotionsProductsViewModel =
(marketPromocji.Areas.DELIVER.Models.PromotionsProductsViewModel)Session[User.Identity.Name];
produkty produkt = new produkty();
produkt = unitOfWork.ProduktyRepository.GetByID(productId);
promocje_produkty promocjeProdukty = new promocje_produkty();
promocjeProdukty.cena_brutto = Convert.ToDecimal(formCollection.Get("cenaZakupuNetto")); //tutaj to jeszcze musze sprawdzic czy to w odpowiedniej kolejnosci jest;/
promocjeProdukty.cena_brutto_dla_sklepu = Convert.ToDecimal(formCollection.Get("cenaZakupuBrutto"));
promocjeProdukty.cena_netto = Convert.ToDecimal(formCollection.Get("cenaSprzedazyNetto"));
promocjeProdukty.cena_netto_dla_sklepu = Convert.ToDecimal(formCollection.Get("cenaSprzedazyBrutto"));
string zielonyKoszyk = formCollection.Get("zielonyKoszyk");
if(zielonyKoszyk==null)
{
promocjeProdukty.czy_zielony_koszyk = false;
}
else
{
promocjeProdukty.czy_zielony_koszyk = true;
}
promocjeProdukty.ref_produkt = productId;
promocjeProdukty.ref_promocja = promotionId;
try
{
unitOfWork.PromocjeProduktyRepository.Insert(promocjeProdukty);
unitOfWork.Save();
}
catch(Exception ex)
{
}
return RedirectToAction("TesotwanieTabelki", new { promotionId=promotionId});
}
I cant figured out how to show whole page after Ajax call to Controler. After 'Order' buton click I call javascript function where I make Ajax call to controler action to get XML in string and with that string I call another controller action where I return model. In last step I want to call third controller action with return View(model) but I get null object parameter.
function order(model) {
$('#details-container').html("<h2>Loading Complete Frame Module. Please wait...</h2>");
$.p({
url: '#Url.Action("CompleteFrameBrandDetails", "PacCompleteFrame")',
data: { item: model },
success: function (xml) {
if (xml.Success) {
$.p({
url: '#Url.Action("GlassCompleteFrame", "PacModule")',
data: JSON.stringify({ b2bXml: xml.Data }),
success: function (model) {
var pacModuleModel = {
CustomerNumber: model.Data.CustomerNumber,
Language: model.Data.Language,
Comission: model.Data.Comission,
GlassXml: model.Data.GlassXml,
Price: model.Data.Price,
ReadOnly: model.Data.ReadOnly,
Mode: model.Data.Mode,
IframeUrl: model.Data.Mode
};
var url = '#Url.Action("GlassCompleteFrameView", "PacModule", "__view__")';
window.location.href = url.replace("__view__", JSON.stringify(pacModuleModel));
}
});
} else {
$.alert({
message: 'error while trying to load xml details'
});
}
}
});
}
public ActionResult GlassCompleteFrame(string b2bXml)
{
string mode = "5";
//If the Store isn't selected, redirect to HomePage
if (string.IsNullOrEmpty(_workContext.SelectedCustomerNumber))
{
return RedirectToRoute("HomePage");
}
else
{
PacModuleModel model = new PacModuleModel();
model.CustomerNumber = _workContext.SelectedCustomerNumber;
model.Language = _workContext.WorkingLanguage.UniqueSeoCode;
model.Comission = "";
if (b2bXml == null || b2bXml == String.Empty)
{
return RedirectToRoute("HomePage");
}
else
{
model.GlassXml = b2bXml.Replace("\"", "\\\"");
}
int index = b2bXml.IndexOf("<price>") + "<price>".Length;
string p = b2bXml.Substring(index, b2bXml.IndexOf("</price>") - index);
model.Price = Convert.ToDouble(p, System.Globalization.CultureInfo.InvariantCulture);
model.ReadOnly = false;
model.Mode = ModuleMode.ByProduct;
model.IframeUrl = "http://ItkCompleteConfiEmbedded.aspx?lang=" + _workContext.WorkingLanguage.LanguageCulture; //_pacGeneralSettings.GlassModuleUrl + ;
return new JsonResult()
{
Data = new
{
Success = true,
Data = model
}
};
}
}
public ActionResult GlassCompleteFrameView(PacModuleModel model)
{
// here I get null model parameter
return View("Glass", model);
}
Curently I don't know how to pass model to the last action controller. Thank you nice people for help.
If I understand correctly, something like this should do the trick:
Let's say you have, in your controller MyModelController:
public ActionResult SomePage(MyModel myModel){
return View(myModel);
}
To naviguate to that page, you could do:
<script>
window.location.href = "#Url.Action("SomePage", "MyModel", myModelObject)";
</script>
I hope this helps!
I use Session variable to get model in GlassCompleteFrameView(PacModuleModel model) and works perfect. I set Session variable in public ActionResult GlassCompleteFrame(string b2bXml).
public ActionResult GlassCompleteFrameView(PacModuleModel model)
{
model = Session["xml"] as PacModuleModel;
return View("Glass", model);
}
I've been trying to make the "RedirecttoAction" statement work here but it doesn't budge. Here is the method:
[HttpPost]
public ActionResult UpdateTech(int tech, int id)
{
Callout callout = db.Callouts.Find(id);
callout.TechnicianId = tech;
callout.TechStatus = "ASSIGNED";
db.Entry(callout).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("CalloutAdmin/Index/");
}
And it is called by the following JQuery, which works perfectly:
$(function () {
$(".techdropdown").change(function () {
var recordToUpdate = $(this).attr("id");
var selectedTech = $(".techdropdown option:selected").val();
window.alert(selectedTech);
$.post("/CalloutAdmin/UpdateTech?tech=" + selectedTech + "&id=" + recordToUpdate);
});
});
The only thing that does not happen is the page being refreshed, which was what the redirect should do. Can anyone advise?
UPDATE
What I am trying to do is update this Callout object, without redirecting to another view. I choose a technician from a dropdownlist and it automatically sets the callout's technician value to the one I chose from the dropdown.
You're returning the redirect to the AJAX request, and the AJAX request is loading the page in the background. If you want to have the entire page redirect you probably want to use the success callback in jQuery
$.post("/CalloutAdmin/UpdateTech?tech=" + selectedTech + "&id=" + recordToUpdate, function() { document.location = "CalloutAdmin/Index/"; } );
If you want to have the action control the location of the redirect, you probably want to use the return a JsonResult or ContentResult from your action with the URL outputted from there have jQuery's success callback redirect the user.
Assuming that UpdateTech and Index both belong to CallOutAdminController then change your UpdateTech Method to look like:
[HttpPost]
public ActionResult UpdateTech(int tech, int id)
{
Callout callout = db.Callouts.Find(id);
callout.TechnicianId = tech;
callout.TechStatus = "ASSIGNED";
db.Entry(callout).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index","CallOutAdmin");
}
Then make you jQuery function like this:
$(document).ready(function(e) {
$(".techdropdown").change(function () {
var recordToUpdate = $(this).attr("id");
var selectedTech = $(".techdropdown option:selected").val();
window.alert(selectedTech);
window.location = "/CallOutAdmin/UpdateTech?tech=" + selectedTech + "&id=" + recordToUpdate
});
});