Passing data to controller and changing the view - view

I have the following scenario:
I have a table with a list of book. Now, when I click on the selected rows, I want to send the book titles to the rental controller so that the controller can then call the appropriate view pass the book titles.
Here's the code for the table view:
<button id="checkoutButton">Checkout</button>
<table id="books" class="table table-bordered table-hover">
<thead>
<tr>
<th>Book</th>
<th>Category</th>
<th>Author</th>
<th>Registration Number</th>
<th>Volume</th>
<th>Number In Stock</th>
<th>Number Available</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
}
#section Scripts{
<script>
$(document).ready(function () {
var titles = [];
var table = $("#books").DataTable({
ajax: {
url: "/api/books",
dataSrc: ""
},
columns: [
{
data: "title"
},
{
data: "categoryId"
},
{
data: "registrationNumber"
},
{
data: "volume"
},
{
data: "numberInStock"
},
{
data: "numberAvailable"
},
{
data: "author"
}
]
});
$('#checkoutButton').click(function () {
var obj = table.rows('.selected').data();
if (obj.length == 0)
console.log("No row selected");
else {
for (var i = 0; i < table.rows('.selected').data().length; i++) {
console.log(table.rows('.selected').data()[i].title);
titles.push(table.rows('.selected').data()[i].title);
}
$.ajax({
url: "/Rental/print",
contentType: 'application/json',
method: "POST",
data: JSON.stringify({ titles })
})
}
});
And here's the controller:
public ActionResult print(Object [] titles)
{
for(var i = 0; i < titles.Length; i++)
{
Debug.WriteLine(titles[i]);
}
return View("New");
}
I haven't passed the title to the view yet because the view is not rendering at all. I have verified that the controller does get the data but it does not navigate to the "New.html". Although, if I manually navigate to this page, it does render. So, I am really not sure what I am doing wrong here.
I will very much appreciate if you can point me to the right direction.
Note: I have not included the js code which selects multiple rows because I wanted to keep the code simple. Let me know if I need to show that too.

Related

Pass JSON data (by using Ajax ) to table in View Laravel

I am new to Laravel and trying to self learn the same for inhouse project.
Trying to pass json data to table for showing the data in the same. Data received in json is ok but not able to put the same in Table
Controller:
public function getmilkrecordforbid(Request $req)
{
$bidformilk = $req->bidformilkrecord;
$bmilkrecord = buffalomilkrecord::where('buffaloID', '=', $bidformilk)-
>get();
return ($bmilkrecord);
}
web.php
Route::post('/getmilkrecordforbid'[BuffalodataController::class,'getmilkrecordforbid'])
ajax file
$('#selectid').on('change', function() {
var bidformilkrecord = $('#selectid').val();
$.ajax({
url : '/getmilkrecordforbid',
dataType : "json",
method : "POST",
data : {'bidformilkrecord': bidformilkrecord, "_token":"{{
csrf_token()}}"},
success: function(data){
console.log(data)
console.log(data.length)
},
});
});
console.log
(4) [{…}, {…}, {…}, {…}]0: {id: 5, buffaloID: 'Buffalo-02', date: '2020-12-15', milkmorning: '5.00', milkevening: '6.00', …}1: {id: 6, buffaloID: 'Buffalo-02', date: '2020-12-16', milkmorning: '5.00', milkevening: '5.00', …}2: {id: 7, buffaloID: 'Buffalo-02', date: '2020-12-17', milkmorning: '5.00', milkevening: '5.00', …}3: {id: 8, buffaloID: 'Buffalo-02', date: '2020-12-18', milkmorning: '5.00', milkevening: '5.00', …}length: 4[[Prototype]]: Array(0)
Table html
<table id="milksummery" class="table table-bordered table-hover table"
style="width:100%">
<thead>
<tr>
<th>Date</th>
<th>Morning Milk</th>
th>Evening Milk</th>
<th>Total Milk</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Your guidance will really help me.......
You just need to manipulate the DOM on the success event. We are getting the first tbody element and adding more elements to it.
Here it is your code with the updated DOM.
$('#selectid').on('change', function() {
var bidformilkrecord = $('#selectid').val();
$.ajax({
url : '/getmilkrecordforbid',
dataType : "json",
method : "POST",
data : {
'bidformilkrecord': bidformilkrecord,
"_token": "{{ csrf_token() }}"
},
success: function(data){
console.log(data)
console.log(data.length)
let tbody = document.getElementsByTagName("tbody")[0];
for (let i = 0; i < data.length; i++) {
let milkSummeryRow = tbody.insertRow();
let dateCell = milkSummeryRow.insertCell();
let dateText = document.createTextNode(data[i]['date']);
dateCell.appendChild(dateText);
let milkMorningCell = milkSummeryRow.insertCell();
let milkMorningText = document.createTextNode(data[i]['milkmorning']);
milkMorningCell.appendChild(milkMorningText);
let milkEveningCell = milkSummeryRow.insertCell();
let milkEveningText = document.createTextNode(data[i]['milkevening']);
milkEveningCell.appendChild(milkEveningText);
let milkTotalCell = milkSummeryRow.insertCell();
let milkTotalText = document.createTextNode(parseFloat(data[i]['milkmorning']) + parseFloat(data[i]['milkevening']));
milkTotalCell.appendChild(milkTotalText);
}
},
});
});

DataTables jquery.dataTables.min.js:181 Uncaught TypeError: Cannot read property 'length' of undefined

I can't specify what/where is the problem, here is my code :
HTML :
<table id="companies" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th class="center">
Id
</th>
<th>RegNo</th>
<th>Name</th>
<th class="hidden-480">Industry</th>
<th class="hidden-phone">
Size
</th>
<th class="hidden-480">LineOfDefence</th>
<th>Address</th>
</tr>
</thead>
</table>
Server side :
var result = new
{
rows = (from company in db.Company.ToList()
select new
{
id = company.CompanyId,
RegNo = company.RegestrationNumber,
Name = company.Name,
Industry = company.IndustryType.Name,
Size = company.CompanySize.Name,
LineOfDefence = company.LineOfDefence.Name,
Address = company.Address
}).ToArray()
};
return Json(result, JsonRequestBehavior.AllowGet);
and here is my Ajax Call :
<script>
$(document).ready(function ()
{
$('#companies').DataTable( {
"ajax": {
url: "/Company/GetCompanyGrid",
type: "GET",
dataType: "json"
}
});
});
</script>
I'm getting this error : "jquery.dataTables.min.js:181 Uncaught TypeError: Cannot read property 'length' of undefined"
note : I'm using jquery-1.12.3.js & DataTables 1.10.12.
Any help would be appreciated .
finally I've figured out the problem :
first : datatables expects specific format, so I changed my server side code like this :
var result = new
{
**draw = 1,
recordsTotal = db.Company.ToList().Count,
recordsFiltered = db.Company.ToList().Count,**
data = (from company in db.Company.ToList()
select new
{
Id = company.CompanyId,
RegNo = company.RegestrationNumber,
Name = company.Name,
Industry = company.IndustryType.Name,
Size = company.CompanySize.Name,
LineOfDefence = company.LineOfDefence.Name,
Address = company.Address,
}).ToArray()
};
return Json(result
, JsonRequestBehavior.AllowGet);
second : I've added these lines to my script
<script>
$(document).ready(function ()
{
$('#companies').DataTable( {
"ajax": {
url: "/Company/GetCompanyGrid",
type: "GET",
dataType: "json"
},"columns": [
{ "data": "Id" },
{ "data": "RegNo" },
{ "data": "Name" },
{ "data": "Industry" },
{ "data": "Size" },
{ "data": "LineOfDefence" },
{ "data": "Address" },
{ "data": "Logo" },
{ "data": null },
]
});
});
</script>
and now it's working perfectly.
Datatables expects the returned json to be in a specific format, as per the documentation - see the 'Returned data' section.
Your json should look something like this:
return Json(new
{
param.draw,
recordsTotal = result.Count,
recordsFiltered = result.Count,
data = result
}, JsonRequestBehavior.AllowGet);
The error is probably a result of datatables looking for a field that isn't present. Note that the draw value is sent in the original GetCompanyGrid() request, you don't need to generate it yourself.

MVC3 reloading part of page with data razor

I have a table with my data from base and 3 buttons to delete, create and update which return PartialViews.
I want to update the part of my page with data after clicking the submit button in the corresponding dialog (delete, update, ...).
What is the easiest way to achive this?
This is what I've got now
I will just add, delete is mostly the same.
<div id="delete-dialog" title="Delete Product"></div>
<script type="text/javascript" >
$(".deleteLink").button();
var deleteLinkObj;
// delete Link
$('.deleteLink').click(function () {
deleteLinkObj = $(this);
var name = $(this).parent().parent().find('td :first').html();
$('#delete-dialog').html('<p>Do you want delete ' + name + ' ?</p>');
//for future use
$('#delete-dialog').dialog('open');
return false; // prevents the default behaviour
});
$('#delete-dialog').dialog({
dialogClass: "ConfirmBox",
autoOpen: false, width: 400, resizable: false, modal: true, //Dialog options
buttons: {
"Continue": function () {
$.post(deleteLinkObj[0].href, function (data) { //Post to action
if (data == '<%= Boolean.TrueString %>') {
deleteLinkObj.closest("tr").hide('fast'); //Hide Row
}
else {
}
});
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
</script>
And after dialog close I want something like a reload of a part of the page.
The data looks like
<table>
<tr>
<th> Name </th>
<th> Date </th>
<th> </th>
</tr>
#foreach (var m in this.Model)
{
<tr>
<td>
<div class="ProductName">#Html.DisplayFor(Model => m.Name)</div>
</td>
<td>
#Convert.ToDateTime(m.AddDate).ToShortDateString()
</td>
<td>
<div class="ProductPrice">#string.Format("{0:C}", m.Price)</div>
</td>
<td>
<div class="CategoryName">#Html.DisplayFor(Model => m.CategoryName)</div>
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = m.ID }, new { #class = "editLink" })
#Html.ActionLink("Delete", "Delete", new { id = m.ID }, new { #class = "deleteLink" })
</td>
</tr>
}
</table>
I'm not sure if im doing this well
I tried to put this action after click the button but nut sure if is right
I changed the Index to a Partial View
buttons: {
"Continue": function () {
$.post(deleteLinkObj[0].href, function (data) { //Post to action
if (data == '<%= Boolean.TrueString %>') {
deleteLinkObj.closest("tr").hide('fast'); //Hide Row
}
else {
}
});
$.ajax.ActionLink("Index",
"Index", // <-- ActionMethod
"Shop", // <-- Controller Name.
new { }, // <-- Route arguments.
null // <-- htmlArguments .. which are none. Y
)
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
I suggest you use the ASP.NET MVC ActionLink helper in your .cshtml file, and not jQuery:
[...]
<script type="text/JavaScript">
function openPopup()
{
// Set your options as needed.
$("#yourPopupDialogId").dialog("open");
}
</script>
[...]
#Ajax.ActionLink(
"Delete",
"Delete",
"Controller",
new { someValue = 123 },
new AjaxOptions
{
// Set your options as needed
HttpMethod = "GET",
UpdateTargetId = "yourPopupDialogId",
OnSuccess = "openPopup()"
}
)
[...]
<div id="yourPopupDialogId" style="display: none;"></div>
Now in your Controller for the methods you want to use for your popups you should return PartialViews:
public ActionResult Delete(int id)
{
RecordDeleteModel model = YourRepository.GetModel( id );
return PartialView( model );
}

Passing Id from javascript to Controller in mvc3

How to pass Id from javascript to Controller action in mvc3 on ajax unobtrusive form submit
My script
<script type="text/javascript">
$(document).ready(function () {
$("#tblclick td[id]").each(function (i, elem) {
$(elem).click(function (e) {
var ID = this.id;
alert(ID);
// var url = '#Url.Action("Listpage2", "Home")';
var data = { Id: ID };
// $.post(url,data, function (result) {
// });
e.preventDefault();
$('form#myAjaxForm').submit();
});
});
});
</script>
the how to pass Id on using $('form#myAjaxForm').submit(); to controller
instead of
$.post(url,data, function (result) {
// });
My View
#using (Ajax.BeginForm("Listpage2", "", new AjaxOptions
{
UpdateTargetId = "showpage"
}, new { #id = "myAjaxForm" }))
{
<table id="tblclick">
#for (int i = 0; i < Model.names.Count; i++)
{
<tr>
<td id='#Model.names[i].Id'>
#Html.LabelFor(model => model.names[i].Name, Model.names[i].Name, new { #id = Model.names[i].Id })
<br />
</td>
</tr>
}
</table>
}
</td>
<td id="showpage">
</td>
I would avoid using the Ajax Beginform helper method and do some pure handwritten and Clean javascript like this
<table id="tblclick">
#foreach(var name in Model.names)
{
<tr>
<td id="#name.Id">
#Html.ActionLink(name.Name,"listpage","yourControllerName",
new { #id = name.Id },new { #class="ajaxShow"})
</td>
</tr>
}
</table>
<script>
$(function(){
$(".ajaxShow")click(function(e){
e.preventDefault();
$("#showpage").load($(this).attr("href"));
});
});
</script>
This will generate the markup of anchor tag in your for each loop like this.
<a href="/yourControllerName/listpage/12" class="ajaxShow" >John</a>
<a href="/yourControllerName/listpage/35" class="ajaxShow" >Mark</a>
And when user clicks on the link, it uses jQuery load function to load the response from thae listpage action method to the div with id showPage.
Assuming your listpage action method accepts an id parameter and returns something
I am not sure for $.post but I know window.location works great for me.
Use this instead and hopefully you have good results :)
window.location = "#(Url.Action("Listpage2", "Home"))" + "Id=" + ID;
replace $('form#myAjaxForm').submit(); with this code and nothing looks blatantly wrong with your jscript.
Just use a text box helper with html attribute ID.
#Html.TextBox("ID")
You can do this too:
var form = $('form#myAjaxForm');
$.ajax({
type: "post",
async: false,
url: form.attr("action"),
data: form.serialize(),
success: function (data) {
// do something if successful
}
});

partial view refresh using jQuery

On my main edit view I have 3 partial views that contain child data for the main view model. I also have html text boxes for entering and saving related data such as notes etc.
After an item is entered or select and passed to a controller action, how do I refresh my partial views? Here is the code I have so far but it does not work. I think I need to pass a model back with my partial view?
I am using ajax to call my controller method.
Partial View:
#model cummins_db.Models.CaseComplaint
<table width="100%">
<tr>
<td>
#Html.DisplayFor(modelItem => Model.ComplaintCode.ComplaintCodeName)
</td>
<td>
#Html.DisplayFor(modelItem => Model.ComplaintCode.ComplaintType)
</td>
</tr>
</table>
This is the html where the partial view is located:
<div class="editor-label">
#Html.Label("Search and select a complaint code")
</div>
<div class="textarea-field">
<input id = "CodeByNumber" type="text" />
</div>
#Html.ActionLink("Refresh", "Edit", new { id = Model.CasesID })
<table width="100%">
<tr>
<th>Complaint Code</th>
<th>Complaint Description</th>
</tr>
#try
{
foreach (var comp_item in Model.CaseComplaint)
{
<div id="complaintlist">
#Html.Partial("_CaseComplaintCodes", comp_item)
</div>
}
}
catch
{
}
</table>
Here is the controller method that returns the partial view.
public ActionResult SelectForCase(int caseid, int compid, string compname)
{
if (ModelState.IsValid)
{
CaseComplaint c = new CaseComplaint
{
CasesID = caseid,
ComplaintCodeID = compid
};
db.CaseComplaints.Add(c);
db.SaveChanges();
}
return PartialView("_CaseComplaintCodes");
}
jQuery ajax calling the controller, it is part of an autocomplete function select.
$('#CodeByNumber').autocomplete(
{
source: function (request, response) {
$.ajax({
url: "/Cases/CodeByNumber", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.ComplaintType,
value: item.ComplaintCodeName,
id: item.ComplaintCodeID
}; //return
}) //map
); //response
} //success
}); //ajax
}, //source
select: function (event, ui) {
var url = "/Cases/SelectForCase";
$.ajax({
type: "GET",
dataType: "html",
url: url,
data: { caseid: $('#CaseID').val(), compid: ui.item.id, compname: ui.item.label },
success: function (result) { $('#complaintlist').html(result); }
});
},
minLength: 1
});
Should the partial view not be as below:
#model cummins_db.Models.CaseComplaint
<table width="100%">
<tr>
<td>
#Html.DisplayFor(m => m.ComplaintCodeName)
</td>
<td>
#Html.DisplayFor(m => m.ComplaintType)
</td>
</tr>
</table>
This is what I ended up doing to make it work. I changed by controller action to this:
public ActionResult SelectForCase(int caseid, int compid)
{
if (ModelState.IsValid)
{
CaseComplaint c = new CaseComplaint
{
CasesID = caseid,
ComplaintCodeID = compid
};
db.CaseComplaints.Add(c);
db.SaveChanges();
var m = from d in db.CaseComplaints
where d.CasesID == caseid
select d;
return PartialView("_CaseComplaintCodes", m);
}
return PartialView("_CaseComplaintCodes");
}
It works now

Resources