I am trying to send the data of my table with dynamic values to the controller.
<tbody>
#if (ViewBag.data != null)
{
foreach (var item in ViewBag.data)
{
<tr>
<td class="AutoId">#item.AutoID <input type="hidden" name="AutoID" value="#item.AutoID" /></td>
<td class="hove" name="text"> <b>#item.Text</b><br /><label></label></td>
<td class="Active">#item.Active</td>
<td id="oBy" name="OrderBy">#item.OrderBy</td>
</tr>
}
}
above is the table structure
I am using below ajax call to send one field for example...
<script>
$(document).ready(function () {
alert("Test 1");
$("#btnSave").click(function (e) {
alert("Test 2");
$.ajax({
type: "POST",
url: '#Url.Action("LookupManagementUpdate", "Admin", new { Area = "Admin" })',
data: $(".hove").val(),
dataType: 'json',
async: false,
success: function (response) {
Success = true;
},
error: function (response) {
},
});
});
});
</script>
Below is my controller code
public string LookupManagementUpdate(string text)
{
return "answer"+Request["text"]+text;
}
I tried using both Request and parameter method to fetch the data but it does not display the table data.
This is a c# mvc ado.net based project
try using Ajax.BeginForm and ajaxOptions Onsuccess
Related
I just recently learned Django/ajax/datatables. I can project my data using a {%for%} loop and im trying to do the same thing with ajax calls.
My view:
def is_ajax(request):
return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest'
def getfromServer(request):
if is_ajax(request=request) and request.method == "GET":
books= Book.objects.all()
bookserial = serializers.serialize('json', books)
return JsonResponse(bookserial, safe=False)
return JsonResponse({'message':'Wrong validation'})
index.html
<div class="container">
<table id="books" class="display" style="width:100%">
<thead>
<tr>
<th>Book</th>
<th>Author</th>
<th>Genre</th>
<th>Date Publishedd</th>
<th>Copies</th>
</tr>
</thead>
</table>
</div>
<script>
$(document).ready(function() {
$('#books').DataTable({
ajax: {
type: "GET",
datatype : 'json',
url: 'views/getfromServer',
},
columns: [
{ data: 'name' },
{ data: 'author' },
{ data: 'genre' },
{ data: 'pub_date' },
{ data: 'copies' },
]
});
</script>
Im pretty sure it kinda works this way but i just cant figure it out .
jQuery DataTable is a powerful and smart HTML table enhancing plugin provided by jQuery JavaScript library
So it doesn't make sense to put an ajax request inside the .DataTable() method
You have to make the ajax request first:
$.ajax({
type: "GET",
datatype : 'json',
url: 'views/getfromServer',
success: function (result) { // result is the response you get from the server if successful
// Use the data in result to write the values to your html table respectively here
}
error: function (err) {
// handle error
}
})
thats what I came up with but still doesnt seem to do the trick all i get is an empty table .
$.ajax({
type: "GET",
datatype : 'json',
url: "views/getfromServer", // "{% url 'index' %}"
success: function (response) {
var instant = JSON.parse(response[books]);
for book in books {
var fields= instant[book]["fields"];
$("#books tbody").prepend(
`<tr>
<td>${fields["name"]||""}</td>
<td>${fields["author"]||""}</td>
<td>${fields["genre"]||""}</td>
<td>${fields["pub_date"]||""}</td>
<td>${fields["copies"]||""}</td>
</tr>`
)
}
},
error: function (response) {
alert(response["responseJSON"]["error"]);
}
})
$(document).ready(function() {
$('#books').DataTable();
So I have a string that has been passed from JS to my controller like so:
JavaScript
function findEmployees(userCounty) {
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("getCounty", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
});
}
Controller
[HttpPost]
public ActionResult Index([FromBody] string userCounty)
{
var county = userCounty.Substring(0, userCounty.IndexOf(" "));
var query = from m in _context.model where m.county == county select new Model
{
FirstName = m.Firstname
LastName = m.LastName
};
if (query == null)
{
return NotFound();
}
return View(query.ToList());
}
[HttpGet]
public ActionResult Index()
{
return View();
}
View
#model Project.Models.ModelName
<table class="table">
<tbody>
<tr>
<td>
#Html.DisplayFor(model => model.FirstName) #Html.DisplayFor(model => model.LastName)
</td>
</tr>
</tbody>
I am able to pass the string from JS to my controller and query the database but how do I update the page to show the results of the query in my view? Anything helps. Thank you!
The data returned by ajax is text or json. If you want to use c# to update the page. You can make action getCounty return partial view, partial view automatically returns data with html.
Change action getCounty.
[HttpPost("getCounty")]
public ActionResult Index([FromBody] string userCounty)
{
var county = userCounty.Substring(0, userCounty.IndexOf(" "));
//...
return PartialView(query.ToList());
}
PartialView Index.cshtml
#model List<ModelName>
<table class="table">
<tbody>
#for (var i = 0; i < Model.Count; i++)
{
<tr>
<td>
#Html.DisplayFor(model => model[i].FirstName) #Html.DisplayFor(model => model[i].LastName)
</td>
</tr>
}
</tbody>
</table>
View
#model ModelName
<div id="datalist">
</div>
<!--other code-->
#section Scripts{
<script>
function findEmployees(userCounty) {
$.ajax({
type: "POST",
//dataType: "json",
url: '#Url.Action("getCounty", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
success: function (data) {
$('#datalist').html(data)
},
error: function (e) {
console.log(e)
}
});
}
</script>
}
It can generate different data tables according to userCounty
You can get the list to the page like this.You can then press inside a div or ul list with each loop.
function findEmployees(userCounty) {
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("getCounty", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
success: function (result) {
if (result.data.length !== 0) {
$.each(result.data, function (index, value) {
var firstName = value.firstName;
var lastName = value.lastName;
});
}
},
});
}
Hi i want to post just a simple string to a controller action in asp.net mvc5.
Im trying to do this for hours and cant find a solution on how it works.
I have tried many different solutions without one of them working in how I want.
For hours...
I have a simple view:
#{
ViewBag.Title = "Rollen und Rechte";
}
<form>
<table cellpadding="5">
<tr>
<td>Rollenname:</td>
<td><input type="text" name="Name" id="roleNameVal" />Rollenname</td>
</tr>
</table>
<br />
<label id="resultLabel"></label>
<input type="submit" value="Submit" id="btn_click" />
<div id="mydiv"></div>
</form>
#section scripts {
<script type="text/javascript">
$('#btn_click').click(function ()
{
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
data: { "val1": val1 },
success: function (data) {
alert(data);
}
})
}
</script>
}
The thing is that the function is never called.
What is wrong here?
And... in the next step I want to update div id mydiv
How can I change that without return a complete view in the controller and force a reload?
Thanks in advance :)
You are missing a closing parenthesis right before your closing </script> tag:
<script type="text/javascript">
$('#btn_click').click(function ()
{
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
data: { "val1": val1 },
success: function (data) {
alert(data);
}
})
}**)**
</script>
instead of using button click event use the following
$(document).on("submit", "form", function (event) {
alert("jas");
var val1 = $('#roleNameVal').val();
$.ajax({
type: "post",
url: "/Create/Role",
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
alert(data);
},
error: function (xhr, desc, err) {
}
})
}
you can use ajax.BeginForm of mvc
like this :
#using (Ajax.BeginForm("YourActionName", "YourControllerName", new AjaxOptions {
InsertionMode = InsertionMode.Replace, //target element(#mydiv) will be replaced
UpdateTargetId = "mydiv"
}))
{
<table cellpadding="5">
<tr>
<td>Rollenname:</td>
<td><input type="text" name="Name" id="roleNameVal" />Rollenname</td>
</tr>
</table>
<br />
<label id="resultLabel"></label>
<input type="submit" value="Submit" id="btn_click" />
}
<div id="mydiv"></div>
and in yourController :
public PartialViewResult YourActionName(string name)
{
return PartialView("_YourPartialView");
}
_YourPartialView is a partial View that you want to return replace it with "mydiv" And how to make it with VIEW is the same
if your partial view has a model you should do this :
return PartialView("_YourPartialView",yourModel);
This is my code in Razor view that basically displays the table by extracting information from database -
#model List<EmpoyeeInfo.Models.FFX_HR_Employees>
#using System.Reflection;
#{
ViewBag.Title = "Employee Information";
var Properties = Model[0].GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance).ToList();
string[] head = new string[Properties.Count()];
}
<div id="web-top">
<div id="horizontal-line"></div>
<input class="search-box-text" type="text" spellcheck="false" placeholder="Search Individual Record..." title="Search Individual Record" id="searchbox" name="searchbox" />
</div>
<div id="web-main">
<table class="employee-info">
<tr>
#foreach (var Property in Properties)
{
if (Property.Name.Equals("AnnualHolidayEntitlement"))
{
<th colspan="2">#Property.Name</th>
}
else
{
<th>#Property.Name</th>
}
}
</tr>
#foreach(var Row in Model)
{
<tr>
#{
Type type = Row.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(type.GetProperties());
}
#foreach (PropertyInfo prop in props)
{
if (prop.Name.Equals("AnnualHolidayEntitlement"))
{
<td contenteditable="true">#prop.GetValue(Row, null)</td>
}
else
{
<td>#prop.GetValue(Row, null)</td>
}
}
<td class="saveToDB">SAVE</td>
</tr>
}
</table>
</div>
but as i type in the search box text, an ajax calls are made -
$(document).ready(function () {
$('.search-box-text').keypress(function () {
getReport($(this).html());
});
})
function getReport(Name) {
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'POST',
data: { Name: Name },
dataType: "json",
cache: false,
success: function (result) {
//do stuff;
},
error: function () {
console.log("no display");
}
});
}
now how do i reload the div - "web-main" and update the Model value such that as the user searches for a name, the table also needs to be updated.
Code below will append the results to the div 'web-main'. You need to manipulate the success portion of jQuery in your code
$(document).ready(function () {
$('.search-box-text').keypress(function () {
getReport($(this).html());
});
})
function getReport(Name) {
$.ajax({
url: '#Url.Action("Index", "Home")',
type: 'POST',
data: { Name: Name },
dataType: "json",
cache: false,
success: function (data) {
//do stuff;
console.log(data);
$("web-main").append(JSON.stringify(data));
},
error: function () {
console.log("no display");
}
});
}
I am trying to create a live search using jquery, ajax and laravel. I also use pjax on the same page, this might be an issue?. Quite simply it should query the database and filter through results as they type.
When using Ajax type:POST I am getting 500 errors in my console. I get zero errors using GET but instead of returning in #foreach it will a full page view (this might be because of pjax).
Where am I going wrong?
Route:
Route::post('retailers/{search}', array(
'as' => 'search-retailers', 'uses' => 'RetailersController#search'));
Controller:
public function search($keyword) {
if(isset($keyword)) {
$data = array('store_listings' => RetailersListings::search($keyword));
return $data;
} else {
return "no results";
}
}
Model:
public static function search($keyword)
{
$finder = DB::table('retailers_listings')
->Where('city', 'LIKE', "%{$keyword}%")
->orWhere('country', 'LIKE', "{$keyword}")
->orderBy('country', 'asc')
->get();
return $finder;
}
View (store.blade.php):
<div id="flash"></div> //loading
<div id="live"> // hide content
<div id="searchword"><span class="searchword"></span></div> //search word
<table class="table">
<tbody>
#foreach($store_listings as $store)
<tr>
<td></td> //echo out all fields eg: {{ $store->name }}
</tr>
#endforeach
</tbody>
</table>
</div>
Form:
<form method="get" action="">
<input type="text" class="search-retailers" id="search" name="search">
</form>
Ajax and JS:
$(function() {
$("#search").keyup(function() {
var keyword = $("#search").val();
var dataString = 'keyword='+ keyword;
if(keyword=='') {
} else {
$.ajax({
type: "GET",
url: "{{ URL::route('search-retailers') }}",
data: dataString,
cache: false,
beforeSend: function(html)
{
document.getElementById("live").innerHTML = '';
$("#flash").show();
$("#keyword").show();
$(".keyword").html(keyword);
$("#flash").html('Loading Results');
},
success: function(html)
{
$("#live").show();
$("#live").append(html);
$("#flash").hide();
}
});
} return false;
});
});
Additional, Here is my controller for pjax, It is important to note I am using the view store.blade.php foreach in for the search and for this store listing.
public function stores($city)
{
$this->layout->header = $city;
$content = View::make('retailers.stores', with(new RetailersService())->RetailersData())
->with('header', $this->layout->header)
->with('store_listings', RetailersListings::stores($city));
if (Request::header('X-PJAX')) {
return $content;
} else {
$this->layout->content = $content;
}
}
Your route is Route::post('retailers/{search}', [...]) and there you go. You pass data to your ajax-call. In GET you get something like url?key=value but using POST the data are added to the request body not to the url.
Knowing this your route is no longer valid since it only looks up for retailers/{search} and not for retailers only (which is the url POST is using).
Well maybe it could help somebody.
As a first problem you are defining the route as POST and then in the ajax request the type GET so it would not work
Also when making POST request Laravel has the csrf check so in order to work, provide it. The js function will be like
$(function() {
$("#search").keyup(function() {
var keyword = $("#search").val();
if(keyword=='') {
} else {
$.ajax({
type: "post",
url: "{{ URL::route('search-retailers') }}",
data: {
'keyword': keywork,
'_token': '{{ csrf_token() }}';
},
dataType: 'html',
cache: false,
beforeSend: function(html)
{
document.getElementById("live").innerHTML = '';
$("#flash").show();
$("#keyword").show();
$(".keyword").html(keyword);
$("#flash").html('Loading Results');
},
success: function(html)
{
$("#live").show();
$("#live").append(html);
$("#flash").hide();
}
});
} return false;
});
});
And you can test your PHP search method doing separate tests for it.