I tried to use reactjs work with C# MVC, and i want to use reactjs ajax to get json array from controller,then show the array elements into select options. But if i use local array, it could show in the select options. I can print out the array element when i use ajax query server method. I do not what happenend.
My view:
<div class="col-md-12">
<div class="col-md-2" id="select">
</div>
</div>
<script type="text/babel">
var Groups = React.createClass({
getInitialState: function () {
return {
data: []
};
},
componentDidMount: function(){
this.serverRequest = $.get(this.props.rout, function(response){
this.setState({
data: response
});
}.bind(this));
},
componentWillUnmount: function(){
this.serverRequest.abort();
},
render () {
return (<select className="selectpicker" multiple="multiple" title="Choose 2-4 colors" data-live-search="true">
{this.state.data.map(function (x) {
console.log(x);
return <ABC value={x} />;
})}
</select>);
}
});
var ABC = React.createClass({
render: function(){
console.log("Option");
console.log(this.props.value);
return <option value={this.props.value}>{this.props.value}</option>;
}
});
ReactDOM.render(
<Groups rout="/CodingManagement/Notification/GroupName" />,
document.getElementById('select')
)
</script>
I could see the console result, but it does not show in view. But if i pass the array to {data}, it could show in the view.
Like this one, it works. I do not know why
<script type="text/babel">
var Groups = React.createClass({
getInitialState: function () {
return {
data: this.props.rout
};
},
render () {
console.log("Groups");
console.log(this.state.data);
return (<select className="selectpicker" multiple="multiple" title="Choose 2-4 colors"
data-live-search="true">
{this.state.data.map(function (x) {
return <ABC value={x}/>;
})}
</select>);
}
});
var ABC = React.createClass({
render: function () {
console.log("Option");
console.log(this.props.value);
return (
<option value={this.props.value}>{this.props.value}</option>
);
}
});
ReactDOM.render(
<Groups rout={["Group4", "Group1", "Group11"]}/>
,
document.getElementById('select')
);
This is server code
public JsonResult GroupName()
{
string[] group = new string[] { "Group4", "Group2", "Group3" };
return Json(group, JsonRequestBehavior.AllowGet);
}
Related
I have not worked with Ajax so far and I want to show the price after selecting the desired option without refreshing the page.
<div class="form-group">
<label class="control-label">choice your Option</label>
<select>
#foreach (var item in Materials)
{
<option value="#item.Id">
#item.MaterialName #item.Panel
</option>
}
</select>
<span class="main-price ">#item.Price</span>
</div>
Lets see what we can do here for your case:
Assign an id to your select to hold the value that you will send your server and span to display the output from the server:
<div class="form-group">
<label class="control-label">choice your Option</label>
<select id="ddlMaterial">
#foreach (var item in Materials)
{
<option value="#item.Id">
#item.MaterialName #item.Panel
</option>
}
</select>
<span class="main-price" id="priceDisplay">#item.Price</span>
</div>
Now we define the AJAX call that will send the request to the server. This request will get the current id of the selected option and then covert it to a JSON string which is sent to the server for processing. The url is the action method which will be invoked on this call:
$(document).ready(function () {
$("#ddlMaterial").change( function (event) {
var id = $(this).val();
var json = {id : id};
$.ajax({
type: 'POST',
url: "#Url.Action("GetPrice", "Home")",
dataType : "json",
data: {"json": JSON.stringify(json)},
success: function(data) {
if(data.status=="true")
{
$("#priceDisplay").text(data.price);
}
else
{
alert('Some error');
}
},
error: function(data) {
alert('Some error');
window.location.reload();
}
});
});
});
And finally your Controller action method will be:
using System.Web.Script.Serialization;
[HttpPost]
public JsonResult GetPrice(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
var id = Convert.ToInt32(jsondata["id"]);
//Get the price based on your id from DB or API call
var getMyPrice=GetPrice(id);
return Json(new {status="true", price= getMyPrice});
}
I want to send parameter when clicking a tag to controller but always null.
How can I get parameters when using datatable ajax? Please help me.
My code in controller:
public JsonResult Getdata(string isvk)
{
var orders = from o in db.Orders
select o;
if (isvk == null)
{
return Json(new { data = orders }, JsonRequestBehavior.AllowGet);
}
switch (isvk)
{
case "canceled":
orders = db.Orders.Where(o => o.Status == -1 || o.Status == -2);
break;
case "pending":
orders = db.Orders.Where(o => o.Status == 0);
break;
case "approved":
orders = db.Orders.Where(o => o.Status == 1);
break;
case "delivered":
orders = db.Orders.Where(o => o.Status == 2);
break;
default:
orders = db.Orders;
break;
}
return Json(new { data = orders.ToList() }, JsonRequestBehavior.AllowGet);
}
Tag <a> is outside the table:
peding
My Script:
var datatable = $("#myTable").DataTable({
ajax: {
type: "GET",
url: "#Url.Action("Getdata","Cart")",
},
columns: [
{ data: "CodeOrder"},
{ data: "FullName"},
{ data: "Email"},
{ data: "Phone" },
]
To send data from DataTables to the server (i.e. to your controller), you use the data option of the ajax function. So, first of all, add that:
ajax: {
type: "GET",
url: "#Url.Action("Getdata","Cart")",
data: function() {
return dataToSend;
}
},
You declare dataToSend as an empty JavaScript object at the start of the document.ready function:
var dataToSend = {};
Here is my simplified version of your <a> tag:
<a id="linkOne" linkData="pending" href="#">submit</a>
Following the dataToSend declaration, I added the following click handler for the <a> tag:
$("a#linkOne").on('click', function() {
event.preventDefault();
var linkDataValue = $( this ).attr( 'linkData' )
dataToSend = { "linkData": linkDataValue };
//console.log( dataToSend );
table.ajax.reload();
});
This code extracts the "pending" text from linkData="pending" in the <a> tag and adds it to the dataToSend object.
Finally, I trigger the DataTable ajax call using reload().
In the controller, this data will be received as a standard URL query parameter (because you are using GET):
linkData=pending
So you can access that in the usual way and format your response accordingly.
In your case, you need to replace my dataToSend logic with your required logic, for your specific <a> tag.
An important point here is that you need to create your dataToSend object correctly.
For one value, it is created as this, as in the above example:
{ "linkData": "pending" }
If you need to send multiple values (e.g. if you are processing a form) then you would build a JavaScript object like this:
[
{
"name": "fieldOne",
"value": "x"
},
{
"name": "fieldTwo",
"value": "y"
}
]
In this case, the object is an array of key-pair values.
For simple forms, the JavaScript serializeArray() function can assist with that - for example:
$( "#formOne" ).on( "submit", function( event ) {
event.preventDefault();
dataToSend = $( "#formOne" ).serializeArray();
//console.log( dataToSend );
table.ajax.reload();
});
UPDATE
In case it helps, here is the full HTML page for my test code.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Personnel</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css">
<link rel="stylesheet" type="text/css" href="https://datatables.net/media/css/site-examples.css">
</head>
<body>
<div style="margin: 20px;">
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Name</th>
<th>Phone</th>
</tr>
</thead>
</table>
<br>
<form id ="formOne">
<input id="fieldOne" type="text" name="fieldOne"></input>
<input id="fieldTwo" type="text" name="fieldTwo"></input>
<input type="submit" value="Submit">
</form>
<br>
<a id="linkOne" linkData="pending" href="#">submit</a>
</div>
<script type="text/javascript">
$(document).ready(function() {
var dataToSend = {};
$( "#formOne" ).on( "submit", function( event ) {
event.preventDefault();
dataToSend = $( "#formOne" ).serializeArray();
//console.log( dataToSend );
table.ajax.reload();
});
$("a#linkOne").on('click', function() {
event.preventDefault();
var linkDataValue = $( this ).attr( 'linkData' )
dataToSend = { linkData: linkDataValue };
//console.log( dataToSend );
table.ajax.reload();
});
var table = $('#example').DataTable( {
ajax: {
url: "http://localhost:7000/personnel",
method: "POST",
data: function( ) {
return dataToSend;
},
dataSrc: ''
},
"columns": [
{ "data": "id" },
{ "data": "firstname" },
{ "data": "name" },
{ "data": "phone" }
]
} );
} );
</script>
</body>
</html>
Welcome to StackOverflow!
You're already very close and the snippets you provided are helpful. What you're missing is that you want the data to update without leaving the page. Using an anchor tag the way you are will direct you to that page. Also, you controller action is returning a JsonResult, which won't return any type of view (but is correct in this case).
You need to add a page event that triggers on clicking the button and refreshes the data source.
There's a few approaches you can take for this, but here's one of them:
<button class="filter-datatable" data-url="#Url.Action("Index","Cart", new {isvk = "pending" })">
// pageScript.js
// jquery, initialization, etc...
$('.filter-datatable').on('click', function() {
var newSource = $(this).data('url');
datatable.ajax.url(newSource).load();
}
Update Script
$(document).ready(function () {
//test
var dataToSend = {};
$("a#linkOne").on('click', function () {
event.preventDefault();
var linkDataValue = $(this).data('id')
var linkurl = $(this).data('url')
dataToSend = { isvk: linkDataValue };
datatable.ajax.reload();
});
var datatable = $("#myTable").DataTable({
ajax: {
type: "GET",
url: "#Url.Action("Getdata","Cart")",
data: function () {
return dataToSend;
}
},
columns: [
{ data: "CodeOrder" },
{ data: "FullName" },
{ data: "Email" },
{ data: "Phone" },
],
});
});
tag <a>:
<a id="linkOne" data-id="pending" href="#">submit</a>
Currently autocomplete is firing, returning empty rows under the textbox.
Empty Rows shown under textbox.
How to get return json values into search textbox?
I need to add more details to get this form to submit.
View
<input type="text" class="sicautocomplete" placeholder="search by SIC Code" />
Controller:
public JsonResult SICCodeSearch(string term)
{
var siccodes = LogicEngineLifetime.Database.SICCodes
.Where(s => s.Code.ToString()
.Contains(term))
.Distinct()
.Select(x => x.Code)
.Take(100)
.ToList();
return Json(siccodes, JsonRequestBehavior.AllowGet);
}
JS:
$(".sicautocomplete").autocomplete({
minLength: 2,
source: function(request, response) {
jQuery.get(sicCodesURL, { term: request.term }, function (data) {
// assuming data is a JavaScript array such as
// ["one#abc.de", "onf#abc.de","ong#abc.de"]
// and not a string
response(data);
});
},
focus: function(event, ui) {
return false;
},
change: function(event, ui) {
if (!ui.item)
$(this).val('');
},
select: function(event, ui) {
var a = ui.item;
$(".sicautocomplete").val("");
return false;
}
});
//$(".sicautocomplete").autocomplete("instance")._renderItem = function (ul, c) {
// return $("<li></li>")
// .data("item.autocomplete", c)
// .append(c)
// .appendTo(ul);
//};
I am using pagedList it is working but i need to have an ajax call to bring a new page i don't know how to do.
public ActionResult ApplicantsRecord(int page =1)
{
List<ApplicantsRecord> ar = new List<ApplicantsRecord>();
ApplicantsRecord a = new ApplicantsRecord();
List<ApplicantsRecordDetailViewModel> apvmlist = new List<ApplicantsRecordDetailViewModel>();
ApplicantsRecordDetailViewModel apvm = new ApplicantsRecordDetailViewModel();
//ar = db.ApplicantsRecords.ToList();
var groupedAR = db.ApplicantsRecords.GroupBy(x => x.SessionId)
.Select(y => new
{
SessionId = y.Key,
ApplicationsRecords = y.FirstOrDefault(),
}).ToList().OrderByDescending(x => x.ApplicationsRecords.LoginDate);
foreach (var i in groupedAR)
{
ar.Add(i.ApplicationsRecords);
}
if(Request.IsAjaxRequest())
{
return PartialView("_ApplicantsRecord", ar.ToPagedList(page, 10));
}
return View(ar.ToPagedList(page, 10));
}
and here is the view code
<div id="pagerecord">
#Html.Partial("_ApplicantsRecord");
</div>
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var getpage = function () {
var $a = $(this);
var options = {
url: $a.attr("href"),
type: "get"
};
$.ajax(options).done(function (data) {
var target = $a.parents("div.pagedList").attr("next");
$(target).replaceWith(data);
});
return false;
};
$('main-conten').on('click', '.pagedList', getpage)
});
</script>
and here is the partial view
<table>
<thead>
<tr>
<th width="220" align="center">
<div class="pagedList" data-back-btn-text="next">
#Html.PagedListPager(Model, page => Url.Action("ApplicantsRecord", new { page }),
PagedListRenderOptions.MinimalWithItemCountText)
</div>
</th>
#*<th width="220" align="center">#Html.DisplayNameFor(model => model.UserName)</th>
<th width="220" align="center">#Html.DisplayNameFor(model => model.LoginDate)</th>
<th width="220" align="center">Details</th>*#
</tr>
</thead>
Did you try this already?
var getpage = function () {
var $a = $(this);
$.ajax({
url: $a.attr("href"),
type: "get",
success: function(data) {
var target = $a.parents("div.pagedList").attr("next");
$(target).replaceWith(data);
},
error: function() {
return false;
}
});
};
Next what you need tot do is:
Try to figure out if the data you are receiving is really the data you are expecting.
See if you do not enter the error function.
The first thing wrong is your selector is not a valid selector. $('main-conten') should probably be $('#main-conten') (assuming it is an element with an id of main-conten).
Secondly, you are using a delegated event handler, but listening for clicks on the .pagedList element and not the anchors within it:
$('main-conten').on('click', '.pagedList', getpage)
but inside the handler you are expecting the anchor to have been clicked as you are using:
var $a = $(this);
and
$a.attr("href")
Try something like this:
$(function () {
// Listen for clicks on anchors inside the paging panel
$('#main-conten').on('click', '.pagedList a', function () {
var $a = $(this);
var options = {
url: $a.attr("href"),
type: "get"
};
$.ajax(options).done(function (data) {
// Do something with the returned data
var target = $a.closest("div.pagedList").attr("next");
$(target).replaceWith(data);
});
return false;
});
});
Notes:
$(function () {YOUR CODE HERE}); is just a handy shortcut for $(document).ready(function(){});
Use closest() in preference to parents() where you only expect a single matching ancestor.
If all this still does not work, please post your HTML output (not source) as saved from the browser.
I have this form-
#using (Html.BeginForm("SaveVideo", "Upload", FormMethod.Post, new { id = "form-upload", #Class = "form-horizontal", enctype = "multipart/form-data", onsubmit = "return tags()", genres = "return genres()" }))
{
}
where on form submit I will need to send strings seperated by comma.
<script type="text/javascript">
function genres() {
var genres = $('#input-genreautocomplete').val();
return genres;
}
function tags() {
var tags = $('#input-tagautocomplete').val();
return tags;
</script>
Now as an example genre would be like- 23,15,16,22,11 as same as tags is. It return me string seperated by comma.
Now I want to use these strings in my method SaveVideo . But I can't get these strings working as parameters. How Do I send these strings on method?
Autocompletes working like this-
<script type="text/javascript">
$(function () {
$('#input-tagautocomplete').tagsinput({
itemValue: 'Id',
itemText: 'TagName',
typeahead: {
source: function (term, process) {
items = [];
map = {};
idofitem = [];
var url = "#Url.Content("~/Upload/GetTagNames/")";
return $.getJSON(url, { term: term }, function (data) {
$.each(data, function (i, item) {
map[item] = item;
items.push(item.TagName);
});
return (items);
});
},
updater: function (item) {
var selected = map[item].Id;
$('#tag-value').val(selected);
return item;
}
}
});
});
</script>
Where updater is not working, though it's bootstrap's typeahead's extension.
I think you are a bit confused. Action parameters don't need to be specified in the BeginForm() helper. In fact, I don't think doing so makes any sense. Firstly, these inputs should be inside your form if they're not already:
#using (Html.BeginForm("SaveVideo", "Upload", FormMethod.Post, new { id = "form-upload", #Class = "form-horizontal", enctype = "multipart/form-data"}))
{
<input type="text" id="input-tagautocomplete" name="tags" />
<input type="text" id="input-genreautocomplete" name="genres" />
}
You could also create these using an HTML helper. The important thing is that they have a value specified for their name attribute.
Then you can just add parameters to your action method to match these names:
public ActionResult SaveVideo(string tags, string genres)
{
// do whatever you want with tags and genres
}