I have made an MVC application which would display a set of file names located in a given directory. To display the list, i have used normal table in my view.Since the view returns a huge list of file names, i am asked to use jquery datatable,which i dont have much idea about. I tried by going through lot of suggestions but could not return the list at all. Please have a look at the code below.
Controller:
public class SupportingChannelController : Controller
{
// GET: SupportingChannel
List<SupportingChannel> _list = null;
SupportingChannelBL _bl = new SupportingChannelBL();
SupportingChannelDataVM _data = new SupportingChannelDataVM();
public ActionResult GetSupportingChannelData()
{
_list = _bl.channel();
_data._model = _list;
return View("SupportingChannel", _data);
}
View
#model MultiRequestInterface.Models.SupportingChannelDataVM
#{
ViewBag.Title = "SupportingChannel";
}
<h2>Supporting Channels</h2>
#using (Html.BeginForm("getComType","SupportingChannel",FormMethod.Post))
{
<div>
<style>
table,th,td
{
border: 1px solid black;
border-collapse: collapse;
align-content:center;
}
</style>
<div style="border:solid;width:100%;overflow-x:auto;">
<table id="table" align="center" style="width:100%" class="display">
<thead>
<tr>
<th>Communication Type</th>
<th>Communication Description</th>
</tr>
</thead>
</table>
</div>
<input type="submit" name="submit" value="submit" />
</div>
if (TempData["testmsg"] != null)
{
<script type="text/javascript">
alert("#TempData["testmsg"]");
</script>
}
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script
src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js">
</script>
<script type="text/javascript">
$(document).ready(function ()
{
var table = $('#table').DataTable();
var data = table.data;
$.ajax({
url: 'GetSupportingChannelData/SupportingChannel',
dataType: 'json',
contentType: "application/json;",
data: JSON.stringify(data),
success: function () {
},
});
});
</script>
Since i am returning a list to the view, i just want some help as in howcan i pass this list as data to the jquery datatable..
Thanks in advance
Since you've already created HTML table containing column headers, just use built-in AJAX call function in DataTable to fetch data as JSON:
$('#table').DataTable({
"ajax": {
"url": "#Url.Action("GetSupportingChannelData", "SupportingChannel")", // action method URL
"type": "GET",
"datatype": "json"
},
, columns: [
{ data: 'columnName1' },
{ data: 'columnName2' },
{ data: 'columnName3' },
{ data: 'columnName4' },
{ data: 'columnName5' }
],
// other settings
});
Then use return type JsonResult to return your list of model as JSON data that will passed to DataTable (I assumed there is another action method which returns view where DataTable should belongs to):
public class SupportingChannelController : Controller
{
List<SupportingChannel> _list = null;
SupportingChannelBL _bl = new SupportingChannelBL();
// other class-level fields
// returns view to render DataTable
public ActionResult GetChannelData()
{
return View();
}
// returns JSON data from list of model values
public ActionResult GetSupportingChannelData()
{
// other stuff
_list = _bl.channel();
// other stuff
return Json(new { data = _list }, JsonRequestBehavior.AllowGet);
}
}
Additional references:
Implement jQuery Datatable in ASP.NET MVC application
AJAX CRUD Operation With jQuery DataTables In ASP.NET MVC 5
Related
I need to change the view in same page using ajax when the user changes the option of the drop-down list.
Up until now in my view I have the drop down list
<div class="wrapper">
<div>
<label>Get cars per people </label>
#Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { #id = "ddlChangeID" })
</div>
<div class="box box-success">
<div class="box-body">
<div>
<canvas id="myChart"></canvas>
</div>
</div>
</div>
</div>
Then in a script (which I found from another question)
$(document).ready(function () {
$("#ddlChangeID").change(function () {
var strSelected = "";
$("#ddlChangeID:selected").each(function () {
strSelected += $(this)[0].value;
});
var url = "/Cars/Index/" + strSelected;
$.post(url, function (data) {
});
});
})
And in the controller I am using ViewBag values to save the drop-down list values and whatever else is needed for the graph which loads in a different script again with ViewBag values. I have managed to pass the selected value (strSelected) but the view does not reload with the new data.
How should I make the ajax event?
Change your script ajax call by calling an action result as follows
$("#ddlChangeID").change(function () {
$.ajax({
url: "/Controller/ActionHtml?id="+$('#ddlChange').val(),
type: "POST",
cache: false,
success: function (result) {
$("#myChart").html(result);
},
error: function () {
$("#myChart").empty();
}
});
});
and in the controller the actionresult will be like the following which returns the html partial view that you need to append
public ActionResult ActionHtml(string id)
{
//Here you can load the data based on the id,pass model to the patial views etc
ViewBag.id = id;
return PartialView("~/Views/Shared/myhtml.cshtml");
}
myhtml.cshtml will be a partial view with the html content as
//content is dummy,change the content as you want
<!DOCTYPE html>
<html>
<body>
<p>Enter some text in the fields below, then press the "Reset form" button to reset the form.</p>
<form id="myForm">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br><br>
</form>
So I changed the
#Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { #id = "ddlChangeID" })
To
#Html.DropDownList("ddlChange", new SelectList(ViewBag.OptionsList,"Value","Text", ViewBag.selectedValue),new { #onchange = "ChangeOption()" })
adding also an id to the main div.
And the script to
function ChangeOption() {
var id = $('#ddlChange').val();
$.ajax({
url: '/Cars/Index',
type: "GET",
data: { Id: id },
success: function (data) {
$('#wrapAll').html(data);
}
});
}
It seems to work. Only issue now is that the css breaks.
It pushes the graph and drop-down list to the right breaking
the functionality.
I'm trying to do what I believe is simple operation/request.
I have a html input text in a view and with Ajax I call the controller to return a partial view with the result of a SQL query with a where clause that comes from the text input, the goal is to retrieve a table with the info.
Below you have the code:
AJAX request from the view to call the controller:
$(function()
{
$.ajax
({
type: "POST",
url: '#Url.Action("result","result")',
data: { Code: result},
success: function(data) {},
error: function(){
alert("error");
}
});
});
Partial view where I receive the model's information but when loaded in the view it does not change, there are no results:
#model xpto.Models.result
#if (Model != null)
{
<h1>Title</h1>
<table>
<tr>
<td>
#Model.Code
</td>
<td>
</td>
</tr>
</table>
}
else
{
<table>
<tr>
<td>
<p>No results</p>
</td>
</tr>
</table>
}
Controller:
Only with the HttpPost to return the Partial View
[HttpPost]
public ActionResult TableStocks(TableStocks model)
{
if (ModelState.IsValid)
{
SqlConnection conn = new SqlConnection(ConnStr);
SqlCommand selectX = new SqlCommand("sqlquery #param"), conn);
SqlDataReader reader;
selectX.Parameters.AddWithValue("#param", model.code);
connection.Open();
reader = selectX.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
model.Code = Int32.Parse(reader["code"].ToString());
}
}
else
{
Console.Write("ERROR");
}
}
return PartialView("result", model);
}
View stays with no results even after the controller receive the value from the input text and retrieve the model with the info from the database.
#Html.Partial("result", Model)
I assume you have verified that the partial view gets the model correctly. If so, then what is left is to modify your AJAX call to replace the partial on the page as such:
$(function()
{
$.ajax
({
type: "POST",
url: '#Url.Action("result","result")',
data: { Code: result},
success: function(data) {
$('#myDiv').html(data); //Add this line to set the data into the page
},
error: function(){
alert("error");
}
});
});
I have a page which is being populated with a list of checkboxes for each record in the database. The user can select as many checkboxes as they want and the system should save their responses. I'm having a hard time getting my array of selected checkboxes to pass through to my Controller.
When i run my code and click the submit button i get a Maximum call stack size exceeded and i'm not sure how to solve that.
Image of the browser console error message: http://imgur.com/a/BnKLL
.cshtml:
#{
ViewBag.Title = "Subject";
}
<head>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
</head>
<h2>Explore Subjects</h2>
<div>
<button id="SubmitButton">Save Changes</button>
<div style="border-bottom:solid">
<h4>Your Followed Subjects</h4>
<div id="FollowedSubjects">
#foreach (var subject in Model.FollowedSubjects)
{
<input type="checkbox" name="SubjectCheckBox" checked="checked" value=#subject.SubjectId>#subject.SubjectDetail.Subject<br>
}
</div>
</div>
<div id="AllSubjects">
<br />
<h4>More Subjects to Follow</h4>
<p>Ordered by number of bills with subject</p>
#foreach(var subject in Model.AllSubjects)
{
<div class="subjectDisp">
<input type="checkbox" name="SubjectCheckBox" value=#subject.Subject.SubjectId>#subject.Subject.Subject (#subject.Count) <br>
</div>
}
</div>
</div>
<script>
$(document).ready(function () {
$('#SubmitButton').click(function () {
var checkboxes = document.getElementsByName("SubjectCheckBox");
var checked = [];
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
checked.push(checkboxes[i]);
}
}
$.ajax({
url: '#Url.Action("FollowSubjects", "Home")',
type: 'POST',
data: { Parameters: checked },
success: function (result) {
alert("success");
},
error: function (result) {
alert("error");
}
});
alert("there")
});
});
</script>
My controller funtion that im trying to call.
[HttpPost]
public ActionResult FollowSubjects(int[] Parameters)
{
int i = 0;
return View();
}
Eventually i will have this hit the database but for now i just put a breakpoint at int i = 0; to see what gets passed to the function.
You can send it as an array of string and convert them to int at server side or Stringify it and send
var checked=""
$(checkboxes).each(function () {
checked += this + ',';
i++;
ajax --> data: { Parameters: checked },
[HttpPost]
public ActionResult FollowSubjects(string Parameters)
{
// Do your task
return View();
}
When I select Date in DateTimePicker, it's invoking public ActionResult Index(DateTime? test). It returns some items into the view, but those items do not appear on Index. It seems that this does not work, and I'm unsure why:
<h1>Items</h1>
#foreach (var item in Model)
{
<br />#item.Date
}
Controller:
public class HomeController : Controller
{
//
// GET: /Home/
public ActionResult Index()
{
List<Table> temp = new List<Table>();
return View(temp);
}
[HttpPost]
public ActionResult Index(DateTime? test)
{
masterEntities m = new masterEntities();
List<Table> temp = m.Table.Where(key => key.Date == test).Select(key => key).ToList();
return View(temp);
}
}
Index.cshtml:
#model IEnumerable<DatePicker.Models.Table>
#{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-2.2.0.min.js"></script>
<script src="~/Scripts/moment.min.js"></script>
<script src="~/Scripts/bootstrap.min.js"></script>
<script src="~/Scripts/bootstrap-datetimepicker.min.js"></script>
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<script type="text/javascript">
$('#datetimepicker1').datetimepicker({ useCurrent: false });
$('#datetimepicker1').on("dp.hide", function (e) {
//var temp = $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm')
$.ajax({
url: "/Home/Index",
type: "POST",
data: { test: $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm') },
//data: {test: temp },
});
});
</script>
</div>
</div>
<h1>Items</h1>
#foreach (var item in Model)
{
<br />#item.Date
}
First you send an empty list to the view:
List<Table> temp = new List<Table>();
return View(temp);
So the loop doesn't show anything because, well, there's nothing to show. It's an empty list.
Then you make an AJAX request to get items:
$.ajax({
url: "/Home/Index",
type: "POST",
data: { test: $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm') },
//data: {test: temp },
});
But you don't do anything with those items. You basically ignore the response from the AJAX request.
So... The data doesn't display because you haven't written any code to display the data. The AJAX request should have some sort of callback function to do something with the returned response:
$.ajax({
url: "/Home/Index",
type: "POST",
data: { test: $('#datetimepicker1').data('DateTimePicker').date().format('YYYY-MM-DD HH:mm') },
//data: {test: temp },
success: function (data) {
// do something with the response here
}
});
What you do with the response is up to you. Is it JSON? HTML? Based on the server-side code, it looks like it's HTML. So you can maybe put it into an element on the page. Something like this, perhaps:
$('#someElement').html(data);
That's just one example, and would of course require an element of some sort that you can identify to hold the response. You could do a lot of other things with the response.
One thing to note, however, is that your response appears to be an entire page. It includes script tags, link tags for CSS, and all sorts of markup that you otherwise already have on the client. So putting the entire page into an element isn't going to work right.
You might want to return just a partial view for this AJAX response. Or, otherwise, instead of using AJAX at all just navigate to the action to get that entire page.
I'm trying to get and pass my ViewModel to my Json method doing the stuff like this :
In my view :
<input type="button" id="suggestionBtn" title="Suggestion" onclick ="location.href='#Url.Action("GetNextAppointment", "Home", new { svm = Model })'" />
In my Controller :
public JsonResult GetNextAppointment(SuggestionViewModel svm)
{
return Json(svm, JsonRequestBehavior.AllowGet);
//this is just for testing
}
While debugging, I found out that my svm is null. I tried to replace it by a string parameter and hard coding the value in my view and this works. So, I don't know very much where is the problem.
Any idea guys?
EDIT : Code edited to use jQuery AJAX
My view's now like this :
#model AstellasSchedulerV2.Models.SuggestionViewModel
<div class="rightPanel">
#using (Html.BeginForm("NewAppointment", "Home", FormMethod.Post, new { #id = "form_ValidateAppointment" }))
{
#Html.Hidden("stringParam","")
<fieldset>
<div>
Patch Anti-douleur Corps #Html.CheckBoxFor(s => s.PADC, new { #class = "checkbox", #id = "chbxPADC" })
</div>
<br />
<div>
Patch Anti-douleur Pied #Html.CheckBoxFor(s => s.PADP, new { #class = "checkbox", #id = "chbxPADP" })
</div>
<br />
Click me
</fieldset>
}
</div>
<script type ="text/javascript">
$(document).ready(function () {
$("#ClickMe").click(function () {
var o = new Object();
o.PADC = $("#chbxPADC").val();
o.PADP = $("#chbxPADP").val();
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJson")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(o),
success: function (data) { alert(data.PADC); },
failure: function (errMsg) { alert(errMsg); }
});
});
</script>
Here goes the solution, Lets say you have your viewmodel this way -
public class SuggestionViewModel
{
public bool PADC { get; set; }
public bool PADP { get; set; }
}
Then you have a View in the following way. Here I used JQuery to make a POST request to GetJson Controller Action. I constructed a JavaScript Object and then serialized it to Json. Then finally passed the Json string to Controller Action.
<fieldset>
<div>
Patch Anti-douleur Corps #Html.CheckBoxFor(s => s.PADC, new { #class = "checkbox", #id = "chbxPADC" })
</div>
<br />
<div>
Patch Anti-douleur Pied #Html.CheckBoxFor(s => s.PADP, new { #class = "checkbox", #id = "chbxPADP" })
</div>
<br />
</fieldset>
This is the JQuery part -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(document).ready(function () {
$("#ClickMe").click(function () {
var chk = $('#chbxPADC').is(':checked');
var chk1 = $('#chbxPADP').is(':checked');
var o = new Object();
o.PADP = chk1;
o.PADC = chk;
jQuery.ajax({
type: "POST",
url: "#Url.Action("GetJson")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(o),
success: function (data) { alert(data.PADP); },
failure: function (errMsg) { alert(errMsg); }
});
});
});
</script>
Click me
And when you click the button, it will hit following controller -
public JsonResult GetJson(SuggestionViewModel svm)
{
return Json(svm, JsonRequestBehavior.AllowGet);
}
And when you inspect the parameter using breakpoint, you will have parameters passed -
And as the response, you will have following output -
You can't post complex objects as parameter.
If you want to get json result, you should call an ajax request.
You should post your model in an ajax request. (you can use jquery .ajax metod), because you cant get values from controller action metod if you use location.href