My Shopping Cart is not working as expected in ASP.NET MVC 5 - asp.net-mvc-5

My cart is working fine in localhost but when i have hosted in cloud hosting it is not working well problem is that when i click add to cart button it will add one product with one quantity but when i add another product in the cart again it will override the previous one and show only one product in cart when i have added on last.. i don't know whats wrong with the sessions it will override the session again i guess. And another problem is that my my update cart button's functionalities and delete button functionalities in cart is not working it throw exception
Object reference not set to an instance of an object.
I have a controller name shoppingCartController here is the code
namespace Medi.Areas.User.Controllers
{
public class ShoppingCartController : Controller
{
ArrayList arr = new ArrayList();
int id;
BLL.IRepository<tbl_Product> de = new BLL.IRepository<tbl_Product>();
public ActionResult Index()
{
return View();
}
private int isExisting(int id)
{
List<Items> cart = (List<Items>)Session["cart"];
for (int i = 0; i < cart.Count; i++)
if (cart[i].Pr.ProductID == id)
return i;
return -1;
}
public ActionResult Delete(int id)
{
int index = isExisting(id);
List<Items> cart = (List<Items>)Session["cart"];
cart.RemoveAt(index);
Session["cart"] = cart;
return PartialView("_pvCart");
}
public ActionResult OrderNow(string q)
{
if (Session["cart"] == null)
{
List<Items> cart = new List<Items>();
cart.Add(new Items(de.GetById(Convert.ToInt32(q)), 1));
Session["cart"] = cart;
// ViewBag.quantity = new MultiSelectList(cart,"Quantity","Quantity");
// cart[1]
}
else
{
id = Convert.ToInt32(q);
List<Items> cart = (List<Items>)Session["cart"];
int index = isExisting(id);
if (index == -1)
cart.Add(new Items(de.GetById(id), 1));
else
cart[index].Quantity++;
Session["cart"] = cart;
// ViewBag.quantity = new MultiSelectList(cart, "Quantity", "Quantity");
}
return View("Cart");
}
[HttpPost]
public ActionResult UpdateCart(int[] ProductID,int [] quantity )
{
int[] x = new int[4];
int[] y = new int[4];
List<Items> cart = (List<Items>)Session["cart"];
for (int i = 0; i < cart.Count; i++)
{
x[i] = ProductID[i];
y[i] = quantity[i];
updcart(x[i],y[i]);
}
Session["cart"] = cart;
return PartialView("_pvCart");
}
public void updcart(int id,int quantity) {
List<Items> cart = (List<Items>)Session["cart"];
int index = isExisting(id);
if (index == -1)
cart.Add(new Items(de.GetById(id), 1));
else
cart[index].Quantity = quantity;
Session["cart"] = cart;
}
}
}
and here is the view name Cart.cshtml
#{
ViewBag.Title = "Cart";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-2.1.4.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
#using (Ajax.BeginForm("UpdateCart", "ShoppingCart", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "MyData", InsertionMode = InsertionMode.Replace }))
{
#Html.AntiForgeryToken()
<br />
<br />
<div id="MyData">
#{Html.RenderPartial("_pvCart");}
and here is the partial view code
#using Medi.Models;
<script src="~/Scripts/metro.min.js"></script>
<table class="table hovered" cellpadding=" 2" cellspacing="2" border="1px">
<tr class="info">
<th></th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Sub Total</th>
</tr>
#{
decimal s = 0;
}
#foreach (Items item in (List<Items>)Session["cart"])
{
<input id="ProductID" name="ProductID" type="hidden" value="#item.Pr.ProductID" />
s = s + (Convert.ToInt32(item.Pr.Price) * item.Quantity);
<tr>
<th>#Ajax.ActionLink("Delete", "Delete", new { id = item.Pr.ProductID }, new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "MyData", InsertionMode = InsertionMode.Replace }, new { #class = "mif-cross" })</th>
<td>#item.Pr.ProductName</td>
<td>#item.Pr.Price</td>
<td>
<input name="quantity" id="quantity" type="text" style="width:25px;" value="#item.Quantity" />
</td>
<td>#(item.Pr.Price * item.Quantity)</td>
</tr>
}
</table><br />
<hr />
<table cellpadding="1px" cellspacing="1px" style="float:right;">
<tr align="center" colspan="5" style="background-color:gray;">
<td><h3 style="padding:1px;">Total</h3></td>
<td> <h3 style="padding:1px;">Rs #s</h3></td>
</tr>
</table>
here is the model class
using BOL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Medi.Models
{
public class Items
{
tbl_Product pr = new tbl_Product();
public tbl_Product Pr
{
get { return pr; }
set { pr = value; }
}
int quantity;
public int Quantity { get; set; }
public Items()
{
}
public Items(tbl_Product product, int quantity)
{
this.Pr = product;
this.Quantity = quantity;
}
}
}
i have also write this code in web.config
<httpCookies httpOnlyCookies="true" requireSSL="true"/>
<sessionState mode="InProc"/>

Related

.NET 6 how to add pages numbers in the view?

I am following the Microsoft tutorial :
https://learn.microsoft.com/fr-fr/aspnet/core/data/ef-mvc/sort-filter-page?view=aspnetcore-6.0
and it works but there is only the button for next and previous...
How to implement the code with the list of the pages numbers between the NEXT and PREVIOUS button?
I created thi code, but i am sure that there is a better way to accomplish this :
<a asp-action="Index"
asp-route-sortOrder="#ViewData["CurrentSort"]"
asp-route-pageNumber="#(Model.PageIndex - 1)"
asp-route-currentFilter="#ViewData["CurrentFilter"]"
class="btn btn-default #prevDisabled">
Previous
</a>
#for (int i = 1; i < Model.TotalPages + 1; i++)
{
if (Model.PageIndex == i)
{
<b>#i.ToString()</b>
}
else
{
<a asp-action="Index"
asp-route-sortOrder="#ViewData["CurrentSort"]"
asp-route-pageNumber="#i.ToString()"
asp-route-currentFilter="#ViewData["CurrentFilter"]"
class="btn btn-default">
#i.ToString()
</a>
}
}
<a asp-action="Index"
asp-route-sortOrder="#ViewData["CurrentSort"]"
asp-route-pageNumber="#(Model.PageIndex + 1)"
asp-route-currentFilter="#ViewData["CurrentFilter"]"
class="btn btn-default #nextDisabled">
Next
</a>
Thanks
You could try LazZiya.TagHelpers .you can find it through Nuget .
Use it in cshtml:
#addTagHelper *,LazZiya.TagHelpers
<paging page-no="Model.PageIndex"
page-size="Model.Pagesize"
total-records="Model.TotalRecords"
>
</paging>
codes in model:
public class PaginatedList<T> : List<T>
{
public int PageIndex { get; private set; }
public int TotalPages { get; private set; }
public int Pagesize { get; private set; }
public int TotalRecords { get; private set; }
public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
{
PageIndex = pageIndex;
TotalRecords = count;
Pagesize = pageSize;
TotalPages = (int)Math.Ceiling(count / (double)pageSize);
this.AddRange(items);
}
public bool HasPreviousPage
{
get
{
return (PageIndex > 1);
}
}
public bool HasNextPage
{
get
{
return (PageIndex < TotalPages);
}
}
public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
{
var count = await source.CountAsync();
var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
return new PaginatedList<T>(items, count, pageIndex, pageSize);
}
}
codes in controller:
public async Task<IActionResult> Index(string sortOrder,string currentFilter,string searchString,int? P)
{
ViewData["CurrentSort"] = sortOrder;
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";
if (searchString != null)
{
P = 1;
}
else
{
searchString = currentFilter;
}
ViewData["CurrentFilter"] = searchString;
var students = from s in _context.Student
select s;
if (!String.IsNullOrEmpty(searchString))
{
students = students.Where(s => s.LastName.Contains(searchString)
|| s.FirstMiddleName.Contains(searchString));
}
switch (sortOrder)
{
case "name_desc":
students = students.OrderByDescending(s => s.LastName);
break;
case "Date":
students = students.OrderBy(s => s.EnrollmentDate);
break;
case "date_desc":
students = students.OrderByDescending(s => s.EnrollmentDate);
break;
default:
students = students.OrderBy(s => s.LastName);
break;
}
int pageSize = 3;
return View(await PaginatedList<Student>.CreateAsync(students.AsNoTracking(), P ?? 1, pageSize));
}
And The result:

the view "Delete" or its master was not found asp.net mvc5

I want to be able to upload a file then to download it or delete it. But when I try to delete it, I get this error:
The view 'Delete' or its master was not found or no view engine supports the searched locations. The following locations were searched:
~/Views/FileUpload/Delete.aspx ,~/Views/FileUpload/Delete.ascx, ~/Views/Shared/Delete.aspx,~/Views/Shared/Delete.ascx, ~/Views/FileUpload/Delete.cshtml, ~/Views/FileUpload/Delete.vbhtml, ~/Views/Shared/Delete.cshtml ,~/Views/Shared/Delete.vbhtml .
[HttpGet]
public ActionResult Delete( string deletedfile)
{
string current_usr = User.Identity.GetUserId();
string fullPath = Request.MapPath("~/Files/" + current_usr + "/" + deletedfile);
if (System.IO.File.Exists(fullPath))
{
System.IO.File.Delete(fullPath);
ViewBag.Message="Deleted";
}
var items = GetFiles();
return View(items);
}
// GET: FileUpload
public ActionResult Index()
{
var items = GetFiles();
return View(items);
}
// POST: FileUpload
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
try
{
string current_usr = User.Identity.GetUserId();
//string path = Path.Combine(Server.MapPath("~/Files/"),
// Path.GetFileName(file.FileName));
var folder = Server.MapPath("~/Files/" + current_usr + "/");
if (!Directory.Exists(folder))
{
Directory.CreateDirectory(folder);
}
string path = Path.Combine(String.Format(folder),
Path.GetFileName(file.FileName));
file.SaveAs(path);
ViewBag.Message = "File uploaded successfully";
}
catch (Exception ex)
{
ViewBag.Message = "ERROR:" + ex.Message.ToString();
}
else
{
ViewBag.Message = "You have not specified a file.";
}
var items = GetFiles();
return View(items);
}
public FileResult Download(string downloadedfile)
{
string current_usr = User.Identity.GetUserId();
var FileVirtualPath = "~/Files/" + current_usr + "/" + downloadedfile;
return File(FileVirtualPath, "application/force-download", Path.GetFileName(FileVirtualPath));
}
private List<string> GetFiles()
{
string current_usr = User.Identity.GetUserId();
var dir = new System.IO.DirectoryInfo(Server.MapPath("~/Files/" + current_usr + "/"));
System.IO.FileInfo[] fileNames = dir.GetFiles("*.*");
List<string> items = new List<string>();
foreach (var file in fileNames)
{
items.Add(file.Name);
}
return items;
}
The View :
<h2> File Upload </h2>
#model List<string>
#using (Html.BeginForm("Index", "FileUpload", FormMethod.Post,
new { enctype = "multipart/form-data" }))
{
<label for="file"> Upload </label>
<input type="file" name="file" id="file" />
<br /><br />
<input type="submit" value="Upload" />
<br /><br />
#ViewBag.Message
<br />
<h2>Documents list</h2>
<table style="width:100%">
<tr>
<th> File Name </th>
<th> Link </th>
</tr>
#for (var i = 0; i <= (Model.Count) - 1; i++)
{
<tr>
<td>#Model[i].ToString() </td>
<td>#Html.ActionLink("Download", "Download", new { downloadedfile = Model[i].ToString() }) </td>
<td>
#Html.ActionLink("Delete", "Delete", new { deletedfile = Model[i].ToString() })
</td>
</tr>
}
</table>
}
The issue is that your Delete Controller method is calling View() at the end. That method will attempt to find a view file with the name of the controller method. If you want to show the list of files after the delete you can redirect to your index action like this:
[HttpGet]
public ActionResult Delete(string deletedfile)
{
string current_usr = User.Identity.GetUserId();
string fullPath = Request.MapPath("~/Files/" + current_usr + "/" + deletedfile);
if (System.IO.File.Exists(fullPath))
{
System.IO.File.Delete(fullPath);
ViewBag.Message = "Deleted";
}
return RedirectToAction("Index");
}
See this link from the microsoft Docs for more detail on redirecting
https://learn.microsoft.com/en-us/aspnet/mvc/overview/older-versions-1/views/asp-net-mvc-views-overview-cs

Controlling cart with session

My cart is working fine in localhost but when i have hosted in cloud hosting it is not working well problem is that when i click add to cart button it will add one product with one quantity but when i add another product in the cart again it will override the previous one and show only one product in cart when i have added on last.. i don't know whats wrong with the sessions it will override the session again i guess. And another problem is that my my update cart button's functionalities and delete button functionalities in cart is not working it throw exception
Object reference not set to an instance of an object.
I have a controller name shoppingCartController here is the code
namespace Medi.Areas.User.Controllers
{
public class ShoppingCartController : Controller
{
ArrayList arr = new ArrayList();
int id;
BLL.IRepository<tbl_Product> de = new BLL.IRepository<tbl_Product>();
public ActionResult Index()
{
return View();
}
private int isExisting(int id)
{
List<Items> cart = (List<Items>)Session["cart"];
for (int i = 0; i < cart.Count; i++)
if (cart[i].Pr.ProductID == id)
return i;
return -1;
}
public ActionResult Delete(int id)
{
int index = isExisting(id);
List<Items> cart = (List<Items>)Session["cart"];
cart.RemoveAt(index);
Session["cart"] = cart;
return PartialView("_pvCart");
}
public ActionResult OrderNow(string q)
{
if (Session["cart"] == null)
{
List<Items> cart = new List<Items>();
cart.Add(new Items(de.GetById(Convert.ToInt32(q)), 1));
Session["cart"] = cart;
// ViewBag.quantity = new MultiSelectList(cart,"Quantity","Quantity");
// cart[1]
}
else
{
id = Convert.ToInt32(q);
List<Items> cart = (List<Items>)Session["cart"];
int index = isExisting(id);
if (index == -1)
cart.Add(new Items(de.GetById(id), 1));
else
cart[index].Quantity++;
Session["cart"] = cart;
// ViewBag.quantity = new MultiSelectList(cart, "Quantity", "Quantity");
}
return View("Cart");
}
[HttpPost]
public ActionResult UpdateCart(int[] ProductID,int [] quantity )
{
int[] x = new int[4];
int[] y = new int[4];
List<Items> cart = (List<Items>)Session["cart"];
for (int i = 0; i < cart.Count; i++)
{
x[i] = ProductID[i];
y[i] = quantity[i];
updcart(x[i],y[i]);
}
Session["cart"] = cart;
return PartialView("_pvCart");
}
public void updcart(int id,int quantity) {
List<Items> cart = (List<Items>)Session["cart"];
int index = isExisting(id);
if (index == -1)
cart.Add(new Items(de.GetById(id), 1));
else
cart[index].Quantity = quantity;
Session["cart"] = cart;
}
}
}
and here is the view name Cart.cshtml
#{
ViewBag.Title = "Cart";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="~/Scripts/jquery-2.1.4.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
#using (Ajax.BeginForm("UpdateCart", "ShoppingCart", new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "MyData", InsertionMode = InsertionMode.Replace }))
{
#Html.AntiForgeryToken()
<br />
<br />
<div id="MyData">
#{Html.RenderPartial("_pvCart");}
</div>
<br /><br />
<input id="updatecart" type="submit" value="update Cart" />
}
and here is the partial view code
#using Medi.Models;
<script src="~/Scripts/metro.min.js"></script>
<table class="table hovered" cellpadding=" 2" cellspacing="2" border="1px">
<tr class="info">
<th></th>
<th>Name</th>
<th>Price</th>
<th>Quantity</th>
<th>Sub Total</th>
</tr>
#{
decimal s = 0;
}
#foreach (Items item in (List<Items>)Session["cart"])
{
<input id="ProductID" name="ProductID" type="hidden" value="#item.Pr.ProductID" />
s = s + (Convert.ToInt32(item.Pr.Price) * item.Quantity);
<tr>
<th>#Ajax.ActionLink("Delete", "Delete", new { id = item.Pr.ProductID }, new AjaxOptions() { HttpMethod = "POST", UpdateTargetId = "MyData", InsertionMode = InsertionMode.Replace }, new { #class = "mif-cross" })</th>
<td>#item.Pr.ProductName</td>
<td>#item.Pr.Price</td>
<td>
<input name="quantity" id="quantity" type="text" style="width:25px;" value="#item.Quantity" />
</td>
<td>#(item.Pr.Price * item.Quantity)</td>
</tr>
}
</table><br />
<hr />
<table cellpadding="1px" cellspacing="1px" style="float:right;">
<tr align="center" colspan="5" style="background-color:gray;">
<td><h3 style="padding:1px;">Total</h3></td>
<td> <h3 style="padding:1px;">Rs #s</h3></td>
</tr>
</table>
here is the model class
using BOL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Medi.Models
{
public class Items
{
tbl_Product pr = new tbl_Product();
public tbl_Product Pr
{
get { return pr; }
set { pr = value; }
}
int quantity;
public int Quantity { get; set; }
public Items()
{
}
public Items(tbl_Product product, int quantity)
{
this.Pr = product;
this.Quantity = quantity;
}
}
}
i have also write this code in web.config
<httpCookies httpOnlyCookies="true" requireSSL="true"/>
<sessionState mode="InProc"/>

Model is getting null on post on Child Partial View MVC5

I asked this question in a another thread but i never got the answer. Hope someone bright can help me with this.
Basically what i'm trying is to get TestModel back to ActionResult Questions(TestModel test, FormCollection formCollection). Whenever next button is pressed in _Question.cshtml partial View ActionResult Index(TestModel test) is bounded with empty model therefore i can't get anything from user to fill my testModel. Please Help
///////////////Models//////////////
[Serializable]
public class TestModel
{
private QuestionModel _currenQuestionModel;
public int TestID { get; set; }
public string TestName { get; set; }
public string Instructions { get; set; }
public double TestTime { get; set; }
public QuestionModel CurrenQuestionModel
{
get
{
if (_currenQuestionModel == null &&
Questions != null &&
Questions.Count > 0)
_currenQuestionModel = Questions.First();
return _currenQuestionModel;
}
set { _currenQuestionModel = value; }
}
public List<QuestionModel> Questions { get; set; }
}
public class QuestionModel
{
public int QuestionID { get; set; }
public string Question { get; set; }
public bool HasMultipleAnswers { get; set; }
public IList<PossibleAnswerModel> PossibleAnswers { get; set; }
}
public class PossibleAnswerModel
{
public bool IsSelected { get; set; }
public string DisplayText { get; set; }
}
}
////////////////// Controller /////////////////
public class TestController : Controller
{
public ActionResult Index(int id)
{
var model = _testColletion.FirstOrDefault(r => r.TestID == id);
return View(model);
}
[HttpPost]
public ActionResult Index(TestModel test)
{
//var model = (TestModel) Session["CurrentTest"];
return View(test);
}
[ChildActionOnly]
[HttpGet]
public ActionResult Questions(TestModel test)
{
var testModel = _testColletion.Single(r => r.TestID == test.TestID);
return PartialView("_Start", testModel);
}
[HttpPost]
public ActionResult Questions(TestModel test, FormCollection formCollection)
{
var q = formCollection.Count >2 ? formCollection.GetValues(1):null;
var testModel = _testColletion.FirstOrDefault(r => r.TestID == test.TestID);
//if (questionID == 0)
//{
// testModel.CurrenQuestionModel = testModel.Questions.First();
//}
if (!string.IsNullOrWhiteSpace(Request["next"]))
{
var nextQuestionIndex =
testModel.Questions.FindIndex(r => r.QuestionID == testModel.CurrenQuestionModel.QuestionID) + 1;
testModel.CurrenQuestionModel = testModel.Questions[nextQuestionIndex];
}
else if (!string.IsNullOrWhiteSpace(Request["prev"]))
{
var prevQuestionIndex =
testModel.Questions.FindIndex(r => r.QuestionID == testModel.CurrenQuestionModel.QuestionID) - 1;
testModel.CurrenQuestionModel = testModel.Questions[prevQuestionIndex];
}
return PartialView("_Question", testModel);
}
private static List<TestModel> _testColletion = new List<TestModel>()
{
new TestModel()
{
TestID = 1,
TestName = "ASP.NET",
Instructions = "Please choose from appropriate options",
TestTime = 2.40,
Questions = new List<QuestionModel>()
{
new QuestionModel(){QuestionID = 1, Question = "Question 1"}
}
},
new TestModel()
{
TestID = 2,
TestName = "ASP.NET MVC",
Instructions = "Please choose from appropriate options",
TestTime = 1.00,
Questions = new List<QuestionModel>()
{
new QuestionModel(){QuestionID = 1, HasMultipleAnswers=true, Question = "Question 1", PossibleAnswers = new List<PossibleAnswerModel>()
{
new PossibleAnswerModel(){DisplayText = "Possible Answer 1"},
new PossibleAnswerModel(){DisplayText = "Possible Answer 2"},
new PossibleAnswerModel(){DisplayText = "Possible Answer 3"},
new PossibleAnswerModel(){DisplayText = "Possible Answer 4"},
}},
new QuestionModel(){QuestionID = 2, HasMultipleAnswers=true, Question = "Question 2"},
new QuestionModel(){QuestionID = 3, HasMultipleAnswers=true, Question = "Question 3"},
new QuestionModel(){QuestionID = 4, HasMultipleAnswers=true, Question = "Question 4"},
new QuestionModel(){QuestionID = 5, HasMultipleAnswers=true, Question = "Question 5"},
}
},
new TestModel()
{
TestID = 3,
TestName = "ASP.NET Spring",
Instructions = "Please choose from appropriate options",
TestTime = 1.00,
Questions = new List<QuestionModel>()
{
new QuestionModel(){QuestionID = 1, Question = "Question 1"},
new QuestionModel(){QuestionID = 2, Question = "Question 2"},
new QuestionModel(){QuestionID = 3, Question = "Question 3"},
new QuestionModel(){QuestionID = 4, Question = "Question 4"},
}
},
new TestModel()
{
TestID = 4,
TestName = ".NET C#",
Instructions = "Please choose from appropriate options",
TestTime = 4.40,
Questions = new List<QuestionModel>()
{
new QuestionModel(){QuestionID = 1, Question = "Question 1"},
new QuestionModel(){QuestionID = 2, Question = "Question 2"}
}
}
};
}
/////////// Inside _Question.cshtml partial view///////////////
#model InterviewQ.MVC.Models.TestModel
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
#*#Html.HiddenFor(r => r.CurrentQuestionID)*#
<div>
<br />
<h4>Question #Model.CurrenQuestionModel.QuestionID</h4>
<hr />
<p>#Model.CurrenQuestionModel.Question</p>
</div>
<p>
#if (Model.CurrenQuestionModel.HasMultipleAnswers)
{
#Html.Partial("_MultipleAnswerQuestionView", Model.CurrenQuestionModel)
}
</p>
<p>
#if (Model.CurrenQuestionModel.QuestionID > 0 && Model.CurrenQuestionModel.QuestionID < Model.Questions.Count)
{
if (Model.CurrenQuestionModel.QuestionID > 1)
{
<input type="submit" class="btn btn-default" value="Previous" name="prev" />
}
<input type="submit" class="btn btn-default" value="Next" name="next" />
}
#if (Model.CurrenQuestionModel.QuestionID == Model.Questions.Count)
{
<input type="submit" class="btn btn-default" value="Finish" name="finish" />
}
</p>
}
//////////// Inside _MultipleAnswerQuestionView.cshtml partial view///////////////
#model InterviewQ.MVC.Models.TestModel
#if (!Model.CurrenQuestionModel.HasMultipleAnswers)
{
throw new InvalidOperationException("This answer optioin template doesn't support this type of questions");
}
#for (var i = 0; i < Model.CurrenQuestionModel.PossibleAnswers.Count; i++)
{
<div class="row">
<div class="col-lg-6">
<div class="input-group">
<span class="input-group-addon">
#Html.CheckBoxFor(r => r.CurrenQuestionModel.PossibleAnswers[i].IsSelected)
#*<input type="checkbox" value="#Model.CurrenQuestionModel.PossibleAnswers[i].IsSelected" name="#Model.CurrenQuestionModel.PossibleAnswers[i].IsSelected">*#
</span>
<p>
#Model.CurrenQuestionModel.PossibleAnswers[i].DisplayText
</p>
</div><!-- /input-group -->
</div><!-- /.col-lg-6 -->
</div><!-- /.row -->
}

Asynchronous Task controllers in C#4

I want to write an asynchronous Controller that is displaying in output an IEnumerable<IEnumerable<Video>>
I don't know I can manage to write correctly my function Task<IEnumerable<IEnumerable<Video>>> GetVideosAsync(xxxxx) especially the Task.ContinueWhenAll function (in order not to have blocking code ).
Is it better to use a lambda for this piece of code ...?
Can someone help me ?
Nb: *I can only use C#4 and visual Studio 2010
public class HomeController : AsyncController
{
string[] sources = {
"http://xxxx/membervideos/1",
"http://xxxx/membervideos/2"
};
public Task<ActionResult> Async()
{
var sw = Stopwatch.StartNew();
var data = GetVideosAsync();
sw.Stop();
ViewBag.Elapsed = sw.ElapsedMilliseconds;
return View("~/views/home/index.cshtml", data);
}
Task<IEnumerable<IEnumerable<Video>>> GetVideosAsync()
{
var allVideosTasks = new List<Task<IEnumerable<Video>>>();
foreach (var url in sources)
{
allVideosTasks.Add(DownloadDataAsync(url));
}
var context = TaskScheduler.FromCurrentSynchronizationContext();
Task.Factory.ContinueWhenAll<IEnumerable<Video>,IEnumerable<IEnumerable<Video>>(
/// CODE TO ComplETE HERE
);
Task<IEnumerable<Video>> DownloadDataAsync(string url)
{
var httpClient = new HttpClient();
var httpResponseMessage = httpClient.GetAsync(url);
var result = httpResponseMessage.ContinueWith
(t =>
{
t.Result.EnsureSuccessStatusCode();
return t.Result.Content.ReadAsAsync<IEnumerable<Video>>();
}
).Unwrap();
return result;
}
/**** VIEW ******/
#{
ViewBag.Title = "Home Page";
}
#model IEnumerable<IEnumerable<MvcApplication1.Models.Video>>
<table>
#foreach (var memberVideos in Model)
{
<tr>
#foreach(var video in memberVideos){
<td>
<div>#video.Title</div>
<div><img src="http://xxxxxx/membervideos/#video.ImageUrl" style="width: 185px;"/> </div>
</td>
}
</tr>
}
</table>
<h1>#ViewBag.Elapsed</h1>

Resources