ng-grid in from tag with run at server in aspx page - ng-grid

i am calling the ajax function on click of button it returns the json data and i am passing the data to the main.js script file(controller) its getting the data and binding the data to the ng-grid, the question here is whne i put the ng-grid in the from tag it does not dispaly the data
<script type="text/javascript">
$(document).ready(function () {
$("#mybutton").click(function () {
var scope = angular.element(document.getElementById("wrap")).scope(); // to get access all the varibales defined in the contoller
scope.$apply(function () {
$.ajax({
type: "POST",
url: "Website/Nggrid.asmx/GetDataForNgGrid",
success: function (result) {
// console.log(result);
var fd = JSON.parse(result); //parsing the json string
scope.updateMessage(fd);
alert("hi");
},
error: function (xmlhttprequest, Status, thrownError) {
alert(thrownError.toString());
alert(thrownError);
}
});
});
});
});
</script>
this is the function i am calling when the user clicks on button
<body ng-controller="MyCtrl">
<%--<form id="form1" runat="server">--%>
<div id="wrap" class="gridStyle" ng-grid="gridOptions">
</div>
<button id="mybutton">
Try it</button>
<%-- </form>--%>
</body>
this is the main.js
var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function ($scope) {
$scope.myData = [];
$scope.updateMessage = function (_s) {
$scope.myData = _s;
// $scope.Enable = true;
};
$scope.gridOptions = {
data: 'myData',
columnDefs: [
{ field: 'Status', displayName: 'Status', width: "*" }
]
};
});
my question is here that when i put ng-grid in the from tag it wont show the data, please give the suggestion on this
<form id="form1" runat="server">
<div id="wrap" class="gridStyle" ng-grid="gridOptions">
</div>
<button id="mybutton">
Try it</button>
</form>

Related

How to call an action method upon selection from the <select> dropdwon in ASP.NET Core 6 MVC?

I created a dropdown using the <select> HTML element. Now I want to call an action after user makes a selection from the list.
<select name="ddAircraft" id="ddAircraft" class="form-control form-select-sm form-select"
asp-items="#(new SelectList(ViewBag.ddaircraft,"id","name"))">
</select>
I would also like to know if user enter a value in a input box. Then I want to run a Javascript method. How I can do that?
I tried to do onClick but I am getting usual error.
It would help if you could show the details of your error,
I Tried with the codes below:
#{
var sel = new List<SelectListItem>()
{
new SelectListItem(){Text="1",Value="1" },
new SelectListItem(){Text="2",Value="2" },
new SelectListItem(){Text="3",Value="3" }
};
}
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(function () {
$('#selectlist').change(function () {
window.location.href = "Privacy";
})
});
</script>
<script>
$(function () {
$('#input').change(function () {
window.location.href = "Privacy";
})
});
</script>
<input id="input" value=""></input>
<select id="selectlist" asp-items=sel></select>
The result:
To pass the selected item value ,you could try :
<script>
$(function () {
$('#selectlist').change(function () {
window.location.href = "Home/Privacy?sel=" + $(this).val();
})
});
</script>
The result:
if you want to make a post request, you could try with ajax as below:
<script>
$(function () {
$('#selectlist').change(function () {
var sel = $(this).val();
var input = document.getElementById("input").value;
$.ajax({
url: "Home/Test",
contentType: "application / json; charset = utf - 8",
type: "post",
data: JSON.stringify({
sel: sel,
input: input
}),
datatype: "json",
success: function (data) {
console.log(data);
}
})
})
});
</script>
The result:

React Tutorial - Page Refreshing after Comments Added

I'm working through the official React tutorial and having a little trouble. When I add a comment I expect the comment to appear in the view, and for a split second it does, but then the page refreshes and the comment's gone.
On a related matter (and really just a request for a little FYI as I'm still learning AJAX), the code is supposed to add the comment to the JSON. I'm presuming that this wouldn't work on the Plunker but is there enough code there to actually update a JSON if the page is live?
Thanks for any help! Plunker link and code follows:
https://plnkr.co/edit/p76jB1W4Pizo0rDFYIwq?p=preview
<script type="text/babel">
// To get started with this tutorial running your own code, simply remove
// the script tag loading scripts/example.js and start writing code here.
var CommentBox = React.createClass({
loadCommentsFromServer: function() {
$.ajax({
url: this.props.url,
dataType: 'json',
cache: false,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
handleCommentSubmit: function(comment) {
var comments = this.state.data;
// Optimistically set an id on the new comment. It will be replaced by an
// id generated by the server. In a production application you would likely
// not use Date.now() for this and would have a more robust system in place.
comment.id = Date.now();
var newComments = comments.concat([comment]);
this.setState({data: newComments});
$.ajax({
url: this.props.url,
dataType: 'json',
type: 'POST',
data: comment,
success: function(data) {
this.setState({data: data});
}.bind(this),
error: function(xhr, status, err) {
this.setState({data: comments});
console.error(this.props.url, status, err.toString());
}.bind(this)
});
},
getInitialState: function() {
return {data: []};
},
componentDidMount: function() {
this.loadCommentsFromServer();
setInterval(this.loadCommentsFromServer, this.props.pollInterval);
},
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm onCommentSubmit={this.handleCommentSubmit} />
</div>
);
}
});
var CommentList = React.createClass({
render: function() {
var commentNodes = this.props.data.map(function(comment) {
return (
<Comment author={comment.author} key={comment.id}>
{comment.text}
</Comment>
);
});
return (
<div className="commentList">
{commentNodes}
</div>
);
}
});
var CommentForm = React.createClass({
getInitialState: function() {
return {author: '', text: ''};
},
handleAuthorChange: function(e) {
this.setState({author: e.target.value});
},
handleTextChange: function(e) {
this.setState({text: e.target.value});
},
handleSubmit: function(e) {
e.preventDefault();
var author = this.state.author.trim();
var text = this.state.text.trim();
if (!text || !author) {
return;
}
this.props.onCommentSubmit({author: author, text: text});
this.setState({author: '', text: ''});
},
render: function() {
return (
<form className="commentForm" onSubmit={this.handleSubmit}>
<input
type="text"
placeholder="Your name"
value={this.state.author}
onChange={this.handleAuthorChange}
/>
<input
type="text"
placeholder="Say something..."
value={this.state.text}
onChange={this.handleTextChange}
/>
<input type="submit" value="Post" />
</form>
);
}
});
var Comment = React.createClass({
rawMarkup: function() {
var md = new Remarkable();
var rawMarkup = md.render(this.props.children.toString());
return { __html: rawMarkup };
},
render: function() {
return (
<div className="comment">
<h2 className="commentAuthor">
{this.props.author}
</h2>
<span dangerouslySetInnerHTML={this.rawMarkup()} />
</div>
);
}
});
ReactDOM.render(
<CommentBox url="comments.json" pollInterval={2000} />,
document.getElementById('content')
);
</script>
As you said, your problem is that the information in the json file is static (see last paragraph), so every time the comments are refreshed, you lose the new one. The way you could handle it is using the json file during the first load and then just prevent refreshing them, just adding the new ones to the comment box state (after all this is just a example and you just want to see some eye candy, don't you?).
Checking the browser's console you can see that your AJAX request to store the new file is failing, you cannot update it on Plunker, that file is immutable.

How to use ajax to post Kendo upload files to controller

When i use ajax to post the form data to controller, i cannot get the files when using Kendo upload. I used IEnumerable but i only can get the date value and the file is null. May i know how to make it work? Thanks.
(I use ajax because i need call the onsuccess event)
//Here is the form control in view
<div class="editForm">
#using (Html.BeginForm("UpdateReportFix", "Defect", FormMethod.Post, new { id = "form" }))
{
#Html.HiddenFor(model => model.DefectFixID)
<div>
#Html.Label("Report Date")
</div>
<div>
#(Html.Kendo().DatePickerFor(model => model.ReportDate)
.Name("ReportDate")
.Value(DateTime.Now).Format("dd/MM/yyyy")
.HtmlAttributes(new { #class = "EditFormField" })
)
#Html.ValidationMessageFor(model => model.ReportDate)
</div>
<div>
#Html.Label("Photos")
<br />
<span class="PhotosMessage">System Allow 2 Pictures</span>
</div>
<div class="k-content">
#(Html.Kendo().Upload()
.Name("files") <-----i cannot get this value in controller
)
</div>
<br />
<div class="col-md-12 tFIx no-padding">
#(Html.Kendo().Button().Name("Cancel").Content("Cancel").SpriteCssClass("k-icon k-i-close"))
#(Html.Kendo().Button().Name("submit").Content("Submit").SpriteCssClass("k-icon k-i-tick"))
</div>
}
//script
$('form').submit(function (e) {
e.preventDefault();
var frm = $('#form');
$.ajax({
url: '#Url.Action("UpdateReportFix")',
type: 'POST',
data: frm.serialize(),
beforeSend: function () {
},
onsuccess: function () { },
success: function (result) { },
error: function () { }
});
});
For "Uploading files using Ajax & Retain model values after Ajax call and Return TempData as JSON" try the following example:
View:
#using (Html.BeginForm("Create", "Issue", FormMethod.Post,
new { id = "frmCreate", enctype = "multipart/form-data" }))
{
<div id="divMessage" class="empty-alert"></div>
#Html.LabelFor(m => m.FileAttachments, new { #class = "editor-label" })
#(Html.Kendo().Upload()
.HtmlAttributes(new { #class = "editor-field" })
.Name("files")
)
}
<script>
$(function () {
//Populate model values of the partialview after form reloaded (in case there is a problem and returns from Controller after Submit)
$('form').submit(function (event) {
event.preventDefault();
showKendoLoading();
var selectedProjectId = $('#ProjectID').val(); /* Get the selected value of dropdownlist */
if (selectedProjectId != 0) {
//var formdata = JSON.stringify(#Model); //For posting uploaded files use as below instead of this
var formdata = new FormData($('#frmCreate').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Create", "Issue")',
//contentType: "application/json; charset=utf-8", //For posting uploaded files use as below instead of this
data: formdata,
dataType: "json",
processData: false, //For posting uploaded files we add this
contentType: false, //For posting uploaded files we add this
success: function (response) {
if (response.success) {
window.location.href = response.url;
#*window.location.href = '#Url.Action("Completed", "Issue", new { /* params */ })';*#
}
else if (!response.success) {
hideKendoLoading();
//Scroll top of the page and div over a period of one second (1,000 milliseconds = 1 second).
$('html, body').animate({ scrollTop: (0) }, 1000);
$('#popupDiv').animate({ scrollTop: (0) }, 1000);
var errorMsg = response.message;
$('#divMessage').html(errorMsg).attr('class', 'alert alert-danger fade in');
$('#divMessage').show();
}
else {
var errorMsg = null;
$('#divMessage').html(errorMsg).attr('class', 'empty-alert');
$('#divMessage').hide();
}
}
});
}
else {
$('#partialPlaceHolder').html(""); //Clear div
}
});
});
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)] Model viewModel, IEnumerable<HttpPostedFileBase> files)
{
//...
return Json(new { success = false, message = "Max. file size is 10MB" }, JsonRequestBehavior.AllowGet);
}

passing model from view to controller using jquery

I have a view
#using staffInfoDetails.Models
#model staffInfo
<link href="../../Content/myOwn.css" rel="stylesheet" type="text/css" />
#{staffInfo stf = Model;
}
<div id="education1">
#using (Html.BeginForm("addNewEdu","Home",FormMethod.Post))
{
#Html.HiddenFor(x=>x.StaffId)
<table>
<tr>
<th>Country</th>
<th>Board</th>
<th>Level</th>
<th>PassedYear</th>
<th>Division</th>
</tr>
<tr>
#Html.EditorFor(x => x.eduList)
</tr>
<tr>
#*<td><input type="submit" value="create Another" id="addedu"/> </td>*#
#*<td>#Html.ActionLink("Add New", "addNewEdu", new { Model })</td>*#
</tr>
</table>
}
<button id="addedu">Add Another</button>
</div>
I want to pass the model staffInfo to controller using jquery as below
<script type="text/javascript">
$(document).ready(function () {
$("#addedu").live('click', function (e) {
// e.preventDefault();
$.ajax({
url: "Home/addNewEdu",
type: "Post",
data: { model: stf },//pass model
success: function (fk) {
// alert("value passed");
$("#education").html(fk);
}
});
});
});
</script>
the jquery seems to pass only elements not whole model so how can I pass model from the view to the controller so that I don't have to write the whole parameters list in jquery
u can give ID to the form by using this
#using (Html.BeginForm("addNewEdu", "Home", FormMethod.Post, new { id = "addNewEduForm" }))
{
}
Then in the script
<script type="text/javascript">
$('#addedu').click(function(e) {
e.preventDefault();
if (form.valid()) { //if you use validation
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: $("#addNewEduForm").serialize(),
success: function(data) {
}
});
}
});
</script>
As I can see you trying to submit form with AJAX? Look at serialize function.
$('#addedu').click(function(e) {
e.preventDefault();
var form = $('form');
if (form.valid()) { //if you use validation
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(r) {
}
});
}
});
You can get your values with getElementById then send your action:
$(document).ready(function () {
var select = document.getElementById('...');
$.ajax({
type: "get",
url: "get_street_name",
data: { a: select },
success: function (data) {
$('#result').html(data);
}
});
}

How get the value from a link and send the form using mootools?

I have a such form with many links:
<form name="myform" action="" method="get" id="form">
<p>
My link
</p>
<p>
My link 2
</p>
<p>
My link 3
</p>
<input type="hidden" name="division" value="" />
</form>
I would like to send the form's value from the link that was clicked to php script and get the response (not reloading the page).
I'm trying to write a function that gets the value from a link:
<script type="text/javascript">
window.addEvent('domready', function() {
getValue = function(division)
{
var division;
division=$('form').getElements('a');
}
</script>
but I don't know how to write it in a right way. Next I would like to send the form:
$$('a.del').each(function(el) {
el.addEvent('click', function(e) {
new Event(e).stop();
$('form').submit();
});
});
How I should send it to get the response from a php file not reloading the page?
Instead of putting in javascript inline in the HTML, I would suggest using a delegated event instead. I would also send the form using an ajax call instead of a form submit.
<form id="form">
<a data-value="A">My link</a>
...
</form>
<script>
var formEl = document.id('form');
formEl.addEvent('click:relay(.del)', function() {
var value = this.getProperty('data-value');
new Request.JSON({
url: '/path/to/your/listener',
onSuccess: function(data) {
// ...
}
}).get({
value: value
});
});
</script>
This works for me:
<form id="form">
<a data-value="A">My link</a>
...
</form>
<script>
var links = document.id('form').getElements('a');
links.each(function(link) {
link.addEvent('click', function(e) {
e.stop();
var value = link.getProperty('data-value');
var req = new Request.HTML({
url: "/path/to/your/listener",
data: value,
onRequest: function(){
$('display').set('text', 'Search...');
},
onComplete: function() {
},
update : $('display')
}).get(
{data: value}
);
});
})
</script>

Resources