I have a List in my model. The view is bound to the model. I am trying to populate the List through ajax. And then I have a 'submit' button on the form which should submit the entire model. While submitting the entire model, the list value is 'null'??
I am getting the response data from the controller through Json. The response data is not bound to the model.
<table id="tblTable" style="border-width:1px;border-style:solid" >
<tr style="border-width:1px;border-style:solid">
<th>
#Html.Label("Col1")
</th>
<th>
#Html.Label("Col2")
</th>
</tr>
<tbody>
#if (Model != null && Model.Operations!= null && Model.Operations.Count > 0)
{
foreach (var item in Model.Operations)
{
<tr style="border-width:1px;border-style:solid">
<td style="border-width:1px;border-style:solid">
#Html.DisplayFor(modelItem => item.Col1)
</td>
<td style="border-width:1px;border-style:solid">
#Html.DisplayFor(modelItem => item.Col2)
</td>
</tr>
}
}
</tbody>
</table>
My controller that responds to teh ajax request:
[HttpPost]
public JsonResult UploadFile(HttpPostedFileBase file, Model model)
{
//extract file contents into the operations list
model.Operations = new List<Operations>();
model.Operations.Add(blah..blah)
return Json(model);
}
Issue is, I have to populate the list via ajax, but post the complete model along with the ajax-retrieved data.
Update: JS CODE:
$(document).ready(function () {
$('#fileupload').fileupload({
dataType: 'json',
url: '/Summary/UploadFile',
autoUpload: true,
done: function (e, data) {
var operations = data.result.Operations;
var tbl = $('#tblTable');
$.each(operations, function (key, val) {
$('<tr><td>' + val.col1 + '</td>' + '<td>' +
val.col2 + '</td><tr>').appendTo(tbl);
});
}
}).on('fileuploadprogressall', function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('.progress .progress-bar').css('width', progress + '%');
});
});
Related
I would like to know how you would make an ajax call to another page to show a listing containing the service data
Models.html
<table class="table table-striped">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Model</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Controller
#CrossOrigin
#GetMapping("/cars/{id}/model")
public List<Model> getModels(#PathVariable Long id) {
Optional<Car> car = carRepository.findById(id);
return car.get().getModels();
}
Json
$('table').on('click', 'button[id="model"]', function(e){
var id = $(this).closest('tr').children('td:first').text();
$.ajax({
type:"GET",
enctype: 'application/json',
url:"/cars/" + id + "/model",
success: function(data){
var models = JSON.parse(JSON.stringify(data));
for (var i in models) {
console.log(i);
}
},
error: function(err) {
console.log("Error");
}
});
<h2>GetAllProducts</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Genre)
</th>
<th>
#Html.DisplayNameFor(model => model.AgeId)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
#Html.DisplayFor(modelItem => item.AgeId)
</td>
<td> <button type="button" data-id="#item.Id"
class="productIdButton">AddProductToBasket</button></td>
</tr>
}
#section scripts {
<script type="text/javascript">
$("button").click(function () {
//returns all the product ids
//want to return the selected id of the button clicked
// var h = ($(this).data("id"));
var h= ($(this).attr("data-id"));
var productId = (h.Id);
var s = productId;
//alert(productId);
$.ajax({
url: "/api/BasketAPI/AddProductToBasket/",
type: "POST",
data: { id: productId },
contentType: false,
cache: false,
processData: false,
});
});
</script>
}
I am trying to pass the data-id="#item.Id" value found in the view (JQuery) to the controller and use this value to compare to the Id of a class. I am not sure to get the id value from the ajax request.
[Route("api/BasketAPI/AddProductToBasket/")]
[HttpPost]
public void AddProductToBasket(int id)
{
var returnAllProductIds = _productService.GetProductsById().Where(X=>X.Id==id).Select(x=>x.Id).FirstOrDefault();
At the moment the id from the ajax request (the id is the product id assigned to a button. Each button has a product id assigned to it) is not being passed to the controller. I want the id in the parameter of the method in the controller to be set to the id from the ajax request. At the moment this is not being set.
Please try this.
CSHTML Pages
<h2>GetAllProducts</h2>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Genre)
</th>
<th>
#Html.DisplayNameFor(model => model.AgeId)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
#Html.DisplayFor(modelItem => item.AgeId)
</td>
<td> <button type="button" onclick="AddProductToBasket(#item.Id)" data-id="#item.Id"
class="productIdButton">AddProductToBasket</button></td>
</tr>
}
JavaScript Code
#section scripts {
<script type="text/javascript">
function AddProductToBasket(productid)
{
try
{
$.ajax({
url: "/api/BasketAPI/AddProductToBasket",
type: "POST",
data: { id: productid },
success: function(oData){
alert(oData);
},
error:function(error)
{
alert(error);
}
});
}
catch(e)
{
alert(e.message);
}
}
</script>
}
Controller Action
[Route("api/BasketAPI/AddProductToBasket/")]
[HttpPost]
public int AddProductToBasket(int id)
{
var returnProductId = _productService.GetProductsById().Where(X=>X.Id==id).Select(x=>x.Id).FirstOrDefault();
return returnProductId;
}
this is my wiew****I list my my model here
#model WebApplication2.Models.NewsListQueryModel
<table class="table table-bordered" id="tblNews" >
<thead>
<tr>
<th>Id News</th>
<th>News Time</th>
<th>News Name</th>
<th>News Author</th>
<th>News Content</th>
<th>Değiştir</th>
<th>Sil</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.NewsList)//this part collapse
{
<tr>
<td>#item.IdNews</td>
<td>#item.NewsTime</td>
<td>#item.NewsName</td>
<td>#item.NewsAuthor</td>
<td>#item.NewsContent</td>
<td><a class="btn btn-primary" href="/Author/AuthorList/#item.IdNews">Değiştir</a></td>
<td><a class="btn btn-warning buttonsil " data-id="#item.IdNews" >Sil</a></td>
</tr>
}
</tbody>
</table>
this is my ajax code ı delete item using this ajax code
$("#tblNews").on("click", ".buttonsil", function () {
var btn = $(this);
bootbox.confirm("Silmek istediğinize eminmisiniz", function (result) {
if (result) {
var id = btn.data("id");
$.ajax({
url: "/NewsAdd/Delete/" + id,
type: "GET",
success: function () {
btn.parent().parent().remove();
},
});
}
});
});
this is my controller NewsList I list my my model here Delete item id with ajax cod is removed and deleted here
public ActionResult NewsList()
{
var mod = new NewsListQueryModel();
mod.NewsList = lzm.News.ToList();
return View("NewsList", mod);
}
public ActionResult Delete(int id)
{
var newsdelete = lzm.News.Find(id);
if (newsdelete == null)
{
return HttpNotFound();
}
lzm.News.Remove(newsdelete);
lzm.SaveChanges();
return View("NewsList");
}
this is my model
public class NewsListQueryModel
{
public List<News> NewsList { get; set; }
}
I get the error when I delete an element from the list in wiew.
Error is
System.Web.Mvc.WebViewPage.Model.get returned null .System.NullReferenceException:
In delete action you return ("NewsList"); without model, so in the view model will be null, and the model in foreach will get error.
you can try
#if(Model.NewsList != null && Model.NewsList.Count > 0)
{
}
I have a Ajax Jquery function:
function UpdateValue() {
$(document.body).on("change",".quantity", function () {
var ProID = $(this).attr("data");
var Quantity = $(this).val();
$.ajax({
type: "GET", url: "/Cart/UpdateValue",
data: { ProID: ProID, quantity: Quantity },
success: function (data) {
$("#cartbox").html(data);
}
}
);
$.ajaxSetup({
cache: false
});
});
}
call UpdateValue in Cart Controller:
public PartialViewResult UpdateValue(Cart cart,int ProID, int quantity)
{
List<SelectListItem> items = new List<SelectListItem>();
for (int i = 1; i <= 10; i++)
{
items.Add(new SelectListItem { Text = i.ToString(),
Value = i.ToString() });
}
ViewBag.Items = items;
Product product = repository.Products.FirstOrDefault(p => p.ProductID
== ProID);
if (product != null)
{
cart.UpdateItem(product, quantity);
}
CartIndexViewModel ptview = new CartIndexViewModel { Cart = cart,
ReturnUrl = "/" };
return PartialView(ptview);
}
When the ajax function success, it returns UpdateValue View. But the Dropdown List always changes the same in each row. How can i pass the selected value from the Index View after ajax update?
Here is my UpdateValue View Code:
<table id="cartbox">
<thead>
<tr>
<th>Tên hàng</th>
<th>Số lượng</th>
<th>Đơn giá</th>
<th colspan="2" style="width:70px">Thành tiền</th>
</tr>
</thead>
<tbody>
#foreach (var line in Model.Cart.Lines)
{
<tr>
<td>#line.Product.Name
</td>
<td>#Html.DropDownList("Quantity", new SelectList(ViewBag.Items as System.Collections.IList, "Value", "Text", line.Quantity), new { data = line.Product.ProductID, #class = "quantity" })</td>
<td style="color:#3A9504;margin-left:3px">#string.Format("{0:00,0 VNĐ}", line.Product.Price)</td>
<td>#string.Format("{0:00,0 VNĐ}", (line.Quantity * line.Product.Price))</td>
<td align="center" style="width:10px"><img src="#Url.Content("~/Content/Images/delete.png")" style="padding-right:10px" /></td>
</tr>
}
</tbody>
<tfoot>
<tr style="border-top-style:solid;border-top-color:#DFDFDF;border-top-width:1px;">
<td colspan="3" align="right" style="border-right-color:#808080;border-right-style:solid;border-right-width:1px;text-align:right"><b>Tổng tiền:</b></td>
<td style="text-align: center"><b>#string.Format("{0:00,0 VNĐ}", Model.Cart.ComputeTotalValue())</b></td>
<td></td>
</tr>
</tfoot>
</table>
If I understand you correctly then your problem is that after updating the data in the dropdown list you lose the selection in that dropdown list?
If so then you would need to add this to your success handler in JavaScript:
success: function (data) {
$("#cartbox").html(data);
$("#cartbox").find(".quantity").val(Quantity);
}
I'm having troubles binding new DOM elements to my viewmodel. This elements are in a partial view loaded using an AJAX call (see the customizeQuote function below).
$(function () {
var mvcModel = ko.mapping.fromJS(initialData);
function QuoteViewModel() {
var self = this;
self.customizeQuote = function (quote) {
self.selectedQuote = quote;
//remove the disable attribute on all form controls before serializing data
$(".step").each(function () {
$(this).find('input, select').removeAttr('disabled');
});
//convert form data to an object
var formData = $('#etape').toObject();
$.ajax("getSelectedQuote", {
data: ko.toJSON({ model: self.selectedQuote, model1: formData }),
type: "post", contentType: "application/json",
success: function (result) {
$("#custom").html(result);
$("#etape").formwizard("show", "customize");
ko.applyBindings(self.selectedQuote, $("#covers"));
}
});
}
}
var myViewModel = new QuoteViewModel();
var g = ko.mapping.fromJS(myViewModel, mvcModel);
ko.applyBindings(g);
});
Here's the partial view html:
#model QuoteViewModel
<table id="covers">
<thead>
<tr>
<th>
ProductName
</th>
</tr>
</thead>
<tbody data-bind="foreach: CoverQuotesViewModel">
<tr>
<td>
<input data-bind="value: ProductName" />
</td>
</tr>
</tbody>
</table>
the line:
ko.applyBindings(self.selectedQuote, $("#covers"));
triggers an error:
"ko.applyBindings: first parameter should be your view model; second parameter should be a DOM node"
I'm fairly new to knockout and I don't see what I'm doing wrong. Any idea ?
$("#covers") is not a DOM node though, it is an jQuery object. Perhaps try using this instead:
ko.applyBindings(self.selectedQuote, $("#covers")[0]);
The [0] will get the first matched element of the selector in the jquery object.