Cant withdraw element from collection of EF - c#

i need to select item by id from view to controller and then send item to another view.
My first view, where im send id of item to Edit action:
#foreach (var item in Model)
{
<tr>
<td>
#Html.Raw("<img style='width:80px; height:60px;' src=\"data:image/jpeg;base64,"
+ Convert.ToBase64String(item.Image) + "\" />")
</td>
<td>
#Html.ActionLink("Edit", "Edit", "Personal", new { id = item.Id }, null)
</td>
<td>
#Html.ActionLink("Remove", "Delete", "Personal", new { id = item.Id}, null)
</td>
</tr>
}
My Edit action
public ActionResult Edit(int id)
{
ApplicationUser au = db.Users.Find(User.Identity.GetUserId());
Picture pic = new Picture();
foreach (var item in au.Pictures)
{
if (id == item.Id)
{
pic = item;
}
}
//Picture pic = new Picture { Id = id, Image = image};
return View(pic);
}
And view that wait for item
#model Dip_prj1.Models.Picture
#using Microsoft.AspNet.Identity
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Edit</title>
</head>
<body>
<div>
#Html.Raw("<img style='width:80px; height:60px;' src=\"data:image/jpeg;base64,"
+ Convert.ToBase64String(Model.Image) + "\" />")>
</div>
<div>
#Html.ActionLink("Вернуться к списку", "UserDetails", "Personal", new { id = User.Identity.GetUserId() }, null)
</div>
</body>
</html>
Problem in the Edit controller, cause error write that i send empty byte array. Help me please.

ty all guys for helping, problem was in making Application user type object, i forgot to put part where it must load collection from another table. It should be like ApplicationUser au = db.Users.Include(t => t.Pictures).FirstOrDefault(t => (t.Id) == user);
This Include was clue

Related

asp.net mvc getting data from textbox on view back to stored procedure to edit record

I am new to ASP.NET but have done 20 years of desktop dev. I have a Customer class with fields CustId, CustName, CustNotes.
I have a view called CustView that has some input boxes that are to be pre-populated with customer details from a previous view using the CustID.
I can show the customer details in the text boxes but I cannot get the user edited textboxes (ie the user changes the name of a customer) back to a stored procedure in an Action.
I use a DB class called Cust1DBHandle to call the stored procedure. I have set up 3 buttons and 3 actions in a bid to get any of them to work, either by passing variables or using RequestString but nothing works.
Question #1: how can I pass the new text values back as either global variables, variables in the action or using a datamodel?
Question #2: in the CustViewDBHandle, I populate a list of the results. Is that the correct thing to do if it’s only for one row of data?
Question #3: when pressing a SAVE button that executes a stored procedure, do you have to have a return in the action in the controller?
Thanks.
Cust.cs model
public partial class Cust
{
[DisplayName("Cust ID")]
public Int32 CustID { get; set; }
[DisplayName("Customer Name")]
// [Required(ErrorMessage = "This field is required")]
public string CustName { get; set; }
[DisplayName("Customer Notes")]
public string CustNotes { get; set; }
public string ErrorMessageCust { get; set; }
}
CustView.cshtml:
#model IEnumerable<App22.Models.Cust>
#{
ViewBag.Title = "CustView";
}
<h2>#ViewBag.Title.</h2>
<h3>#ViewBag.Message</h3>
<header>
</header>
<meta name="viewport" content="width=device-width" />
<title>CustViewy</title>
<html>
<head>
</head>
<style>
th, td {
padding: 5px;
}
</style>
<body>
<p>
</p>
<p>CUSTOMER DETAILS ARE HERE</p>
<form name="1" method="post">
<fieldset>
<legend>Headline Details</legend>
<table>
#foreach (var item in Model)
{
<tr>
<td>
<label for="CustID">CustID:</label>
</td>
<td>
<input type="text" name="1CustID" value="#Html.DisplayFor(modelItem =>
item.CustID)" />
</td>
</tr>
<tr>
<td>
<label for="CustName">CustName:</label>
</td>
<td>
<input type="text" name="2CustName" value="#Html.DisplayFor(modelItem
=> item.CustName)" />
</td>
</tr>
<td>
<label for="CustNotes">Cust Notes:</label>
</td>
<td>
<input type="text" name="3CustNotes" value="#Html.DisplayFor(modelItem =>
item.CustNotes)" />
</td>
<tr>
<td></td>
<td>
<input type="submit" name="action:Save1" value="Save" />
<button style="background-color:red" type="button" name="tree0"
class="btn btn-primary" onclick="location.href='#Url.Action("SaveCust0","Cust1")'">
SAVE0 »
</button>
<button style="background-color:blue" type="button" name="tree1"
class="btn btn-primary" onclick="location.href='#Url.Action("SaveCust1","Cust1",new { CustyIDSave = item.CustID , CustyNameSave = item.CustName })'">
SAVE1 »
</button>
<button style="background-color:green" type="button" name="tree2" class="btn btn-primary" onclick="location.href='#Url.Action("SaveCust2","Cust1")'">
SAVE2 »
</button>
</td>
<td>
</td>
</tr>
}
</table>
</fieldset>
</form>
</body>
</html>
Cust1Controller.cs:
public class Cust1Controller : Controller
{
public ActionResult SaveCust0()
{
string message = "";
message = Request.Form["CustName"].ToString();
return Content(message);
CustViewDBHandle dbhandle = new CustViewDBHandle();
ModelState.Clear();
dbhandle.SaveCust(Convert.ToInt32(Request.Form["CustID"]),
Request.Form["CustName"].ToString());
}
public ActionResult SaveCust1(int CustyIDSave, string CustyNameSave)
{
CustViewDBHandle dbhandle = new CustViewDBHandle();
ModelState.Clear();
dbhandle.SaveCust(CustyIDSave, CustyNameSave);
return null;
}
[HttpPost]
public ActionResult SaveCust2(int CustyIDSave, string CustyNameSave)
{
CustViewDBHandle dbhandle = new CustViewDBHandle();
ModelState.Clear();
dbhandle.SaveCust(CustyIDSave, CustyNameSave);
return null;
}
// GET: Cust1
public ActionResult Index()
{
Cust1DBHandle dbhandle = new Cust1DBHandle();
ModelState.Clear();
return View("~/Views/Cust/Cust1.cshtml",dbhandle.GetCust(""));
// return View("~/Views/Cust/Cust1.cshtml"); //This works
}
[HttpGet]
public ActionResult Reload(string tree)
{
//tree = "Breaker2";
Cust1DBHandle dbhandle = new Cust1DBHandle();
ModelState.Clear();
return View("~/Views/Cust/Cust1.cshtml", dbhandle.GetCust(tree));
//Cust1DBHandle dbhandle = new Cust1DBHandle();
//ModelState.Clear();
//return View("~/Views/Cust/Cust1.cshtml", dbhandle.GetCust(SearchBy));
// return View("~/Views/Cust/Cust1.cshtml"); //This works
}
public ActionResult ViewCust(int CustyIDView)
{
//tree = "Breaker2";
CustViewDBHandle dbhandle = new CustViewDBHandle();
ModelState.Clear();
return View("~/Views/Cust/CustView.cshtml", dbhandle.GetCust(CustyIDView));
//Cust1DBHandle dbhandle = new Cust1DBHandle();
//ModelState.Clear();
//return View("~/Views/Cust/Cust1.cshtml", dbhandle.GetCust(SearchBy));
// return View("~/Views/Cust/Cust1.cshtml"); //This works
}
}
CustViewDBHandle.cs:
public class CustViewDBHandle
{
// ********** VIEW CUSTOMER DETAILS ********************
public List<Cust> GetCust(int CustyID)
{
GlobalVar.connection();
List<Cust> CustyChosen = new List<Cust>();
SqlCommand cmd = new SqlCommand("psv_CustView1", GlobalVar.con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CustyID", CustyID);
SqlDataAdapter sd = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
GlobalVar.con.Open();
sd.Fill(dt);
GlobalVar.con.Close();
foreach (DataRow dr in dt.Rows)
{
CustyChosen.Add(
new Cust
{
CustID = Convert.ToInt32(dr["CustID"]),
CustName = Convert.ToString(dr["CustName"]),
CustNotes = Convert.ToString(dr["CustNotes"]),
});
GlobalVar.GlobCustName1 = Convert.ToString(dr["CustName"]); //This method uses
Global Var to get data to pass to form. Can pass anything that way.
}
return CustyChosen;
}
public int SaveCust(int CustyID, string CustyName)
{
GlobalVar.connection();
SqlCommand cmd = new SqlCommand("psu_CustSave1", GlobalVar.con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#CustyID", CustyID);
cmd.Parameters.AddWithValue("#CustyName", CustyName);
GlobalVar.con.Open();
cmd.ExecuteNonQuery();
//SqlDataAdapter sd = new SqlDataAdapter(cmd);
//DataTable dt = new DataTable();
//sd.Fill(dt);
GlobalVar.con.Close();
return 1;
}
}
There is a lot to parse here, but what strikes me as the main part of the problem you have noted is:
a) You methods on the controller are not all decorated with HttpPost attributes.
b) The action on the form that you render will be looking for a POST endpoint with a name that matches the get
That said, you're going to find it hard to get answers for how to make this work, given that this is very non-idiomatic asp.net MVC code.
I would strongly suggest working through a few tutorials, as web dev is considerably different to windows dev, with a different set of challenges. Hopefully your experience will let you skim through that quickly.

How to get Json result in to the table using angularJs

I'm trying to retrieve whole table in mvc5 using angularJS.
Data in Json result is being displayed but not in the table as I wanted.
I'm using mvc5 and angularjs(1.x) to retrive the data from sql server
Here's the Data Access Layer code:
public List<Employee> ShowAllEmployee()
{
List<Employee> prdList = userdb.Employees.ToList();
return prdList;
}
Here's the HomeController method:
public JsonResult AllEmployee()
{
repo = new Employee_DAL.EmpRepo();
var hotList = repo.ShowAllEmployee();
List<Models.Employee> mList = new List<Models.Employee>();
foreach (var hotl in hotList)
{
Models.Employee hotLocal = new Models.Employee();
hotLocal.EmployeeId = hotl.EmployeeId;
hotLocal.FirstName = hotl.FirstName;
hotLocal.LastName = hotl.LastName;
hotLocal.Designation = hotl.Designation;
//hotLocal.Description = hotl.Description;
hotLocal.Country = hotl.Country;
hotLocal.Gender = hotl.Gender;
//hotLocal.Rating = hotl.Rating;
//hotLocal.Email = hotl.Email;
mList.Add(hotLocal);
}
return Json(mList, JsonRequestBehavior.AllowGet);
}
Here's the script ( angular) code:
var myApp = angular.module('MyModule', []);
myApp.controller('DBcontroller', function ($scope, $http) {
$http.get('/Home/AllEmployee') // added an '/' along with deleting Controller portion
.then(function (response) {
$scope.students = response.data
})
})
Here's my view(cshtml):
#{
Layout = null;
}
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/bootstrap")
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Customs/angular.min.js"></script>
<script src="~/Customs/Scripts.js"></script>
<title>AllEmployee</title>
</head>
<body ng-app="myApp">
<div ng-controller="DBcontroller">
<table class="table-bordered">
<tr>
<th>Emp No</th>
<th>First Name</th>
<th>Last Name</th>
<th>Designation</th>
<th>Country</th>
<th>Gender</th>
</tr>
<tr ng-repeat="e in students" #*ng-class-even="'even'" ng-class-odd="'odd'"*#>
<td>{{e.EmployeeId}}</td>
<td>{{e.FirstName}}</td>
<td>{{e.LastName}}</td>
<td>{{e.Designation}}</td>
<td>{{e.Country}}</td>
<td>{{e.Gender}}</td>
</tr>
</table>
</div>
</body>
</html>
I expect the jsonresult to be displayed in a table. Not directly like this in the browser.Screenshot of my current output

getting data from a partial view onto main view

I'm new to the world of ASP.Net MVC and I'm working with a small application that uses many XML files from a web service as its model data. I have an Html page which contains a list of all the tools that are stored in the XML web services. They are within a loop and are clickable links. I also have a partial view which is just a series of text boxes. My goal is to populate the text boxes with information I get from the tool I click while having the list and the text boxes appear on the same page. I have been successful in doing this but so far have only been able to pass the id to a controller which returns my partial view as a completely new page. I'm sure this is a simple solution which may have been answered on here before. What is the best way to go about solving this problem? Below is my model, view(s) and two controllers
Tool Model
public class Tool
{
public int Id { get; set; }
public string ToolId { get; set; }
public string Adapter { get; set; }
public string Description { get; set; }
public string TNumber { get; set; }
public List<string> ComponentList { get; set; }
public List<string> AccessoryList { get; set; }
public List<KeyValuePair<string, string>> ToolIdDescription { get; set; }
public List<string> toolList = new List<string>();
}
Partial View Controller
public ActionResult PartialView()
{
Tool newTool = new Tool();
List<string> tools = new List<string>();
tools = backgroundLoad();
newTool.ToolIdDescription = new List<KeyValuePair<string, string>>();
atool.ToolIdDescription = new List<KeyValuePair<string, string>>();
foreach (string tool in tools)
{
newTool.ToolIdDescription = GetToolDescription(tool);
}
return View(newTool);
}
Controller to recieve Datasets
public ActionResult GetDataSet(string id)
{
Tool selectedTool = new Tool();
if (id != null)
{
var request =
(HttpWebRequest)WebRequest.Create("http://localhost/DbService/Tool/" + id);
XmlDocument xml = new XmlDocument();
Stream aResponsestream;
string aResult = "";
using (aResponsestream = request.GetResponse().GetResponseStream())
using (StreamReader aReader = new StreamReader(aResponsestream,
Encoding.UTF8))
{
aResult = aReader.ReadToEnd();
aResponsestream.Close();
}
xml.LoadXml(aResult);
var Description =
xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Description");
if (Description != null) selectedTool.Description =
Description.InnerText;
var Adapter =
xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Adapter/Name");
if (Adapter != null) selectedTool.Adapter = Adapter.InnerText;
var TNumber =
xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/TNo");
if (TNumber != null) selectedTool.TNumber = TNumber.InnerText;
var ToolId =
xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/ToolId");
if (ToolId != null) selectedTool.ToolId = ToolId.InnerText;
return View(selectedTool);
}
else return View();
}
View which contains the list
#model MiniWeb.Models.Tool
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="~/Content/Site.css" rel="stylesheet" />
</head>
<body>
<h2>Tool List</h2>
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>Id</th>
<th>Description</th>
</tr>
</thead>
#foreach (var item in Model.ToolIdDescription)
{
<tbody>
<tr>
<td>#Html.ActionLink(item.Key, "GetDataSet", new { id = item.Key })</td>
<td>#Html.DisplayFor(modelItem => item.Value)</td>
</tr>
</tbody>
}
</table>
</div>
</body>
</html>
#Html.Partial("GetDataSet", new MiniWeb.Models.Tool())
View which displays the tool information
#model MiniWeb.Models.Tool
#{
ViewBag.Title = "GetDataSet";
}
#{
ViewBag.Title = "Tool";
}
<link href="~/Content/Site.css" rel="stylesheet" />
<h2>Tool Selection </h2>
<div class="Tool">
<span id ="id">
#Html.LabelFor(m => Model.ToolId)
#Html.TextBoxFor(modelItem => Model.ToolId)
</span>
<br/>
<span id="Description">
#Html.LabelFor(m => Model.Description)
#Html.TextBoxFor(modelItem => Model.Description)
</span>
<br/>
<span id="Adapter">
#Html.LabelFor(m=> Model.Adapter)
#Html.TextBoxFor(modelItem => Model.Adapter)
</span>
<br/>
<span id="Adapter">
#Html.LabelFor(m => Model.TNumber)
#Html.TextBoxFor(modelItem => Model.TNumber)
</span>
<span>
<button> Save </button>
</span>
</div>
Sorry for all the code but thank you for reading. I also apologize if this is a really easy solution. I'm just new to ASP.Net and want to develop the best practices instead of doing a hack job on it. Thanks for the help.
With some more research I was able to figure out how to solve my problem. Turns out all I needed was some AJAX. I used an Ajax.Actionlink instead of an HTML action link and was able to load up my partial view in a div on the page. Here is my new view and controller. The partial view stayed the same.
View
#model MiniWeb.Models.Tool
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="~/Content/Site.css" rel="stylesheet" />
<script src="~/Scripts/jquery-3.1.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
</head>
<body>
<h2>Tool List</h2>
<div class="table-responsive">
<table class="table table-hover">
<thead>
<tr>
<th>Id</th>
<th>Description</th>
</tr>
</thead>
#foreach (var item in Model.ToolIdDescription)
{
<tbody>
<tr>
<td>#Ajax.ActionLink(item.Key, "_Partially", new { id = item.Key },new AjaxOptions()
{
HttpMethod = "GET",
UpdateTargetId = "ToolInfo",
InsertionMode = InsertionMode.Replace,
})
</td>
<td>#Html.DisplayFor(modelItem => item.Value)</td>
</tr>
</tbody>
}
</table>
</div>
</body>
</html>
<div id="ToolInfo">
</div>
and my new controller which is returns a PartialView looks like this
Partial View Controller
public PartialViewResult _Partially(string id)
{
Tool selectedTool = new Tool();
if (id != null)
{
var request = (HttpWebRequest)WebRequest.Create("http://localhost/DbService/Tool/" + id);
XmlDocument xml = new XmlDocument();
Stream aResponsestream;
string aResult = "";
using (aResponsestream = request.GetResponse().GetResponseStream())
using (StreamReader aReader = new StreamReader(aResponsestream, Encoding.UTF8))
{
aResult = aReader.ReadToEnd();
aResponsestream.Close();
}
xml.LoadXml(aResult);
var Description = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Description");
if (Description != null) selectedTool.Description = Description.InnerText;
var Adapter = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/Adapter/Name");
if (Adapter != null) selectedTool.Adapter = Adapter.InnerText;
var TNumber = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/TNo");
if (TNumber != null) selectedTool.TNumber = TNumber.InnerText;
var ToolId = xml.SelectSingleNode("RetrieveResponse/RetrieveResult/Tool/ToolId");
if (ToolId != null) selectedTool.ToolId = ToolId.InnerText;
return PartialView("_Partially", selectedTool);
}
return PartialView();
}
Hopefully this answer will help others like me in the future. Thanks for reading.
You're going to want to create a form on your partial view that will submit the data to the main pages controller.
You can find more information in this article.

(Model.CartItems != null) Throwing Object reference not set to an instance of an object do we have any alternative to avoid this?

I have an error in my partial view : Object reference not set to an instance of an object which I tried to bybpass by adding this line but it seems not working because I got the previous mentionned error.
If I put a break point on the added line (#if (Model.CartItems != null)), the first time, the Model is not null (it contains the item I choose, I deleted it, the Model is NULL but the IF statement throw the error Object reference not set to an instance of an object.
I go in my web store, I selected an item and I clicked remove this item. The item is then deleted from the cart table. But the view is not refreshing (the item is still on the screen. But I received a message saying the item ABC was deleted.
I added this line to try to avoid the object reference error for null but doesn't seems to be the proper command to use. Any idea ?
#if (Model.CartItems != null)
TableContent.cshtml partial view
#model Tp1WebStore3.ViewModels.ShoppingCartViewModel
#{
ViewBag.Title = "Table Content";
}
<a Id="TableContent" href="#" class="TableContent">
<table>
<tr>
<th>
Produit
</th>
<th>
Prix (unitaire)
</th>
<th>
Quantite
</th>
<th></th>
</tr>
#if (Model.CartItems != null) <==== line which I added
{
foreach (var item in Model.CartItems)
{
<tr id="row-#item.ProduitId">
<td>
#Html.ActionLink(item.Produit.Description, "Details", "Produit", new { id =
item.ProduitId }, null)
</td>
<td>
#item.Produit.Prix
</td>
<td id="item-count-#item.PanierId">
#item.Quantite
</td>
<td>
Enlever du panier
</td>
</tr>
}
}
<tr>
<td>
Total
</td>
<td></td>
<td></td>
<td id="cart-total">
#Model.CartTotal
</td>
</tr>
</table>
</a>
Index.cshtml from Panier
#model Tp1WebStore3.ViewModels.ShoppingCartViewModel
#{
ViewBag.Title = "Shopping Cart";
}
<script src="/Scripts/jquery-1.8.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$('.RemoveLink').click(function () {
$.ajax({
url: '/Panier/RemoveFromCart',
data: { id: $(this).data('id') },
type: 'POST',
cache: false,
success: function (result) {
$('#row-' + result.DeleteId).remove();
$('#row-' + result.DeleteId).fadeOut('slow');
$('#cart-status').text('Cart (' + result.CartCount + ')');
$('#update-message').text(result.Message);
$('#cart-total').text(result.CartTotal);
$.get('#Url.Action("TableContent", "Panier")')
$("#TableContent").html(data); });
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
return false;
});
});
</script>
<h3>
<em>Details</em> du panier:
</h3>
<p class="button">
#Html.ActionLink("Checkout >>", "AddressAndPayment", "Checkout")
</p>
<div id="update-message">
</div>
<div id="table-content">
#Html.Partial("TableContent") <=== partial view call
</div>
PanierController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tp1WebStore3.Models;
using Tp1WebStore3.ViewModels;
namespace Tp1WebStore3.Controllers
{
public class PanierController : Controller
{
//
// GET: /Panier/
Tp1WebStoreDBEntities dbProduit = new Tp1WebStoreDBEntities();
//
// GET: /ShoppingCart/
public ActionResult Index()
{
var cart = ShoppingCart.GetCart(this.HttpContext);
// Set up our ViewModel
var viewModel = new ShoppingCartViewModel
{
CartItems = cart.GetCartItems(),
CartTotal = cart.GetTotal()
};
// Return the view
return View(viewModel);
}
//
// GET: /Store/AddToCart/5
public ActionResult AddToCart(int id)
{
// Retrieve the album from the database
var addedProduit = dbProduit.Produits
.Single(produit => produit.ProduitId == id);
// Add it to the shopping cart
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCart(addedProduit);
// Go back to the main store page for more shopping
return RedirectToAction("Index");
}
//
// AJAX: /ShoppingCart/RemoveFromCart/5
[HttpPost]
public ActionResult RemoveFromCart(int id)
{
// Remove the item from the cart
var cart = ShoppingCart.GetCart(this.HttpContext);
// Get the name of the album to display confirmation
string produitDescription = dbProduit.Paniers
.Single(item => item.PanierId == id).Produit.Description;
// Remove from cart
int itemCount = cart.RemoveFromCart(id);
// Display the confirmation message
var results = new ShoppingCartRemoveViewModel
{
Message = Server.HtmlEncode(produitDescription) +
" has been removed from your shopping cart.",
CartTotal = cart.GetTotal(),
CartCount = cart.GetCount(),
ItemCount = itemCount,
DeleteId = id
};
return Json(results);
/* return View("CartSummary"); */
}
//
// GET: /ShoppingCart/CartSummary
[ChildActionOnly]
public ActionResult CartSummary()
{
var cart = ShoppingCart.GetCart(this.HttpContext);
ViewData["CartCount"] = cart.GetCount();
return PartialView("CartSummary");
}
public ActionResult TableContent()
{
return PartialView("TableContent");
}
}
}

Select Items and display in same view. Return results to controller

I am new to mvc and fairly young with Javascript so I apologize for the wrong/missing code. I am trying to make a view where the user has a drop down list and items selected via btnAdd will be dynamically displayed in the same view below the btnAdd button. I am assuming the best way to do this would be with JavaScript. After the user has made there choices they will click the btnckout button and there selections will be returned to the controller. Here is what I have so far. I am a little stuck so any help would be appreciated!
View:
#model OnlineTakeout.Models.ProductView
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script src="~/Scripts/jquery-2.1.0.min.js"></script>
<title>Index</title>
</head>
<body>
#using (Html.BeginForm()){
<div>
Pick Product:
<br />
#Html.DropDownListFor(m=>m.ProductId, Model.Products)
<br />
<p>
<input type="button" value="AddToOrder" id="btnAdd" />
</p>
</div>
}
<div>
#using (Html.BeginForm()) {
//Added Items would display here after individual btnAdd button presses
<p>
<input type="button" value="CheckOut" id="btnChkOut" />
</p>
}
</div>
</body>
<script>
$(function () {
$("#btnAdd").click(addProduct);
})
$(function () {
$("#btnChkOut").click(saveProducts);
})
var productList = [];
var id = $("#ProductId").val();
// This function would also display these items on view
function addProduct() {
productList.push(id);
};
function saveProducts() {
$.post("/Product/Index/" + productList());
}
}
</script>
Controller:
public class ProductController : Controller
{
//
// GET: /Product/
public ActionResult Index()
{
var model = new ProductView();
var products = new List<Product> { new Product { ProductId = 1, Name = "Product One", Price = 1.00m },
{ new Product { ProductId = 2, Name = "Product Two", Price = 2.00m } }};
model.Products = new SelectList(products, "ProductId", "Name");
return View(model);
}
[HttpPost]
public JsonResult Index(int[] prodList)
{
return Json("Index");
}
The way I usually do this is by using jQuery.
You will need to create an event handler in jQuery for the change event of your drop down list that is supposed to trigger this change. When that fired, post to an action in your controller that is going to bind a partial controller and return the partial view. It is important to have a return type of ActionResult - that will return the HTML back to success method of your post. Then just embed the HTML on the page and you are done.

Categories