Currently I am working on an ASP.NET Core MVC project. I want to implement in-line editing. Therefore tha plan is to pass the data in a JSON format to the controller and save it. Problem is, I am unable to do so.
My Controller: DenoProfileController
[HttpPost]
public ActionResult Update(DenoProfile denoprofile)
{
DenoProfile emp = db.DenoProfile.Single(em => em.DenoProfileID == denoprofile.DenoProfileID);
emp.NetworkNumber = denoprofile.NetworkNumber;
db.Entry(emp).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("IndexDenoProfile", new { id = 0 });
}
My View:
#model IEnumerable<CRUD_Profile_Creation.Models.ProfileCreationContext>
#{
ViewData["Title"] = "DenoProfile";
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$('.edit-mode').hide();
$('.edit-user, .cancel-user').on('click', function () {
var tr = $(this).parents('tr:first');
tr.find('.edit-mode, .display-mode').toggle();
});
$('.save-user').on('click', function () {
var tr = $(this).parents('tr:first');
var NetworkNumber = tr.find("#NetworkNumber").html();
//Creating Employee JSON object
var EmployeeModel =
{
"NetworkNumber": NetworkNumber,
};
console.log(EmployeeModel.value);
//Posting Employee object to controller's Update action method
$.ajax({
url: "DenoProfile/Update",
data: JSON.stringify(EmployeeModel),
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
tr.find('.edit-mode, .display-mode').toggle();
alert('Record updated Successfully!!');
}
});
});
$('.edit-user').on('click', function () {
var tr = $(this).parents('tr:first');
var NetworkNumber = tr.find("#NetworkNumber").html();
tr.find("#lblNetworkNumber").text(NetworkNumber);
});
})
</script>
<div class="container-fluid" align="center" justify-content="center" style="background-color:white;">
<h1>List of Clients</h1>
<a class="btn btn-success" asp-area="" asp-controller="DenoProfile" asp-action="AddDenoProfile">Profile Creation</a>
<br />
<br />
<table class="table-striped table-bordered">
<thead>
<tr align="center" justify-content="center">
<th>
Deno Profile ID
</th>
<th>
Network Number
</th>
</tr>
</thead>
<tbody>
#foreach (var item in (IEnumerable<CRUD_Profile_Creation.Models.DenoProfile>)ViewBag.DenoProfile)
{
<tr align="center" justify-content="center">
<td>
#Html.DisplayFor(modelItem => item.DenoProfileID)
</td>
<td>
<div class="display-mode" id="lblNetworkNumber">
#Html.DisplayFor(modelItem => item.NetworkNumber)
</div>
<div class="edit-mode">
<input type="text" id="NetworkNumber" value="#item.NetworkNumber" class="edit-mode" />
</div>
</td>
<td>
<button class="edit-user display-mode">Edit</button>
<button class="save-user edit-mode">Save</button>
<button class="cancel-user edit-mode">Cancel</button>
<button class="btn btn-danger"> #Html.ActionLink("Delete Deno Profile", "DeleteDenoProfile", new { id = item.DenoProfileID })</button>
</td>
</tr>
}
</tbody>
</table>
<br />
<br />
<br />
<br />
</div>
Thank you to anyone who can answer or comment my post!
I think I might pass the wrong value into the function. But i am not so sure. This is also my first time trying to pass JSON or anything ajax. If you guys want to leave some tips for me down below, it is very much appreciated.
Related
When i submit the page never stops loading and i have to manually refresh the page to get the input in my table. the table.js and submit.js is in two different components. So how do i make my page automatically refresh alternativly if i could add som eventlistner in the table component to get the API again after a submit.
class Submit extends Component {
render() {
return (
<>
<form action='http://localhost:3001/api/post' method="POST" onsubmit="return false">
<input type="input" class="text" name="brand" placeholder="Brand" required />
<input type="input" class="text" placeholder="Model" required />
<input type="input" class="text" name="price" placeholder="Price" required />
<button type="submit" class='button'>Submit</button>
</form>
</>
)
}
}
function Table() {
useEffect(() => {
Axios.get("http://localhost:3001/api/get/carmodels").then((response) => {
setCarModelList(response.data)
})
}, [])
const [carModelList, setCarModelList] = useState([])
const DeleteCar = (val) => {
const next = [...carModelList];
const removedItems = next.splice(next.indexOf(val), 1);
const deleteCarModel = Axios.delete(`http://localhost:3001/api/delete/${val.id}`);
setCarModelList(next);
return deleteCarModel
}
const renderTableData = () => {
return carModelList.map((val) => (
<tr class>
<td>{val.id}</td>
<td>{val.brand}</td>
<td>{val.model}</td>
<td>{val.price}</td>
<td>
<button id="delete" onClick={() => DeleteCar(val)}>Delete</button>
</td>
</tr>))
}
return (
<table id="table">
<thead>
<tr>
<th>Id</th>
<th>Brand</th>
<th>Model</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{renderTableData()}
</tbody>
</table>
);
}
code exampleAdd UseState for another alert variable that is initialized to false, when you click the submit button, you make it true, and after you fetch, you turn it back to false. example in the image attached
const [alert, setAlert] = useState(true);
const handleSubmit= (e)=> {
setAlert(true)
useEffect(()=>{
// perform your fetch
setAlert(false)
},[alert])
}
Im learnign angularJs, and i want to import an array from a json on my controller Like that:
myApp.controller("demoCtrl", function ($scope, $http) {
var promise = $http.get("todo.json");
promise.then(function (data) {
$scope.todos = data;
});
});
and im using a table to display the data on todos:
<table class="table">
<tr>
<td>Action</td>
<td>Done</td>
</tr>
<tr ng-repeat="item in todos">
<td>{{item.action}}</td>
<td>{{item.done}}</td>
</tr>
</table>
and this results on the flowing html page:
<!DOCTYPE html>
<html ng-app="demo">
<head>
<title>Example</title>
<link href="../css/bootstrap.css" rel="stylesheet" />
<link href="../css/bootstrap-theme.css" rel="stylesheet" />
<script src="angular.js"></script>
<script type="text/javascript">
var myApp = angular.module("demo", []);
myApp.controller("demoCtrl", function ($scope, $http) {
var promise = $http.get("todo.json");
promise.then(function (data) {
$scope.todos = data;
});
});
</script>
</head>
<body ng-controller="demoCtrl">
<div class="panel">
<h1>To Do</h1>
<table class="table">
<tr>
<td>Action</td>
<td>Done</td>
</tr>
<tr ng-repeat="item in todos">
<td>{{item.action}}</td>
<td>{{item.done}}</td>
</tr>
</table>
</div>
</body>
The normal way of getting access to the json is from the data within the returned object from the http request - you are tying to use the entire returned object.
I use "response" as the return from the get request - then the data is "response.data". This is needed because there are other properties returned within the response object from the get request.
Try changing your promise to be as follows:
promise.then(function (response) {
$scope.todos = response.data;
});
Also you should be having a thead and th's and tbody in the table to show a more semantically correct table
<table class="table">
<thead>
<tr>
<th scope="col">Action</th>
<th scope="col">Done</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in todos">
<td>{{item.action}}</td>
<td>{{item.done}}</td>
</tr>
</tbody>
</table>
Promise return entire response in callback Data is in response.data
myApp.controller("demoCtrl", function ($scope, $http) {
var promise = $http.get("todo.json");
// Entire response in callback
promise.then(function (response) {
$scope.todos = response.data; // Data is in response.data
});
});
More: https://docs.angularjs.org/api/ng/service/$http
I need to parse a remote JSON file using a header with a get request in Angular 5. Not sure how to do it with GET along with header.
Something like this but in Angular 5:
let headers = new Headers({
'key': 'Value',
'key2' :'value2'
});
let request_option = new RequestOptions({ headers: this.headers});
this.http.get("http.//.....", request_option)
.map(res => res.json()
this.user.firstname = user.response.docs[0].FIRST_NAME;
this.user.lastname = user.response.docs[0].LAST_NAME;
JSON:
{
"responseHeader": {
"status":0,
"QTime":1,
},"response":{
"docs":[{
"FIRST_NAME": "John",
"LAST_NAME": "Smith"
}]
}
}
& finally be able to call it in HTML:
<div>{{user.firstname}}</div>
Below is the example for getting json from another server
$scope.userData = undefined;
var req = {
method: 'GET',
url: 'https://randomuser.me/api/?results=30&nat=US',
headers: { 'Content-Type': 'application/json' }
};
$http(req).then(function (response) {
$scope.userData = response.data;
});
If the response.data is recieved in json string, you can easily parse it using following code
JSON.stringify(response.data)
Below is the working example for getting json from another server and display it in table
<!DOCTYPE html>
<html>
<head>
<script data-require="jquery#3.0.0" data-semver="3.0.0" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<link data-require="bootstrap#3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
<script data-require="angular.js#1.6.6" data-semver="1.6.6" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.6/angular.min.js"></script>
<script src="https://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js" type="text/javascript"></script>
<script>
(function() {
angular.module("testApp", ['ui.bootstrap']).controller('testCtrl', ['$scope', '$http', function($scope, $http) {
$scope.userData = undefined;
var req = {
method: 'GET',
url: 'https://randomuser.me/api/?results=30&nat=US',
headers: { 'Content-Type': 'application/json' }
};
$http(req).then(function (response) {
$scope.userData = response.data;
});
}]);
}());
</script>
<style></style>
</head>
<body ng-app="testApp">
<div ng-controller="testCtrl">
<form name="commonForm">
<table class="table">
<tr>
<th> Name </th>
<th> Gender </th>
<th> Email </th>
<th> Username </th>
<th> Date of Birth </th>
<th> Registered Date </th>
<th> Phone </th>
<th> Mobile </th>
<th> Nationality </th>
<th> Profile </th>
</tr>
<tr ng-repeat="user in userData.results">
<td> {{user.name.first}} {{user.name.last}}</td>
<td> {{user.gender}}</td>
<td> {{user.email}}</td>
<td> {{user.login.username}}</td>
<td> {{user.dob}}</td>
<td> {{user.registered}}</td>
<td> {{user.phone}}</td>
<td> {{user.cell}}</td>
<td> {{user.nat}}</td>
<td>
<img ng-src="user.picture.large">
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
In Angular 5 you can use property binding to access properties of DOM elements, in test case:
<div [innerHTML]="post.body"></div>
for reference look here angular.io docs
I create a filter on a table. Here the code:
<table id="tableText" class="table table-hover table-striped" ng-init="allNews()">
<tr>
<td colspan="5">
<input type="text" placeholder="Ricerca testo" class="form-control" ng-model="inputText">
</td>
</tr>
<tr>
<th>Titolo</th>
<th>Text</th>
<th>Disattivato</th>
<th>Modifica</th>
<th ng-if="!cancelDelete">Elimina</th>
<th ng-if="cancelDelete">Annulla</th>
</tr>
<tr ng-repeat="news in allNews | filter : inputText">
<td>
<div ng-hide="editingData[news.id]"><span ng-bind-html="news | deleteTitle"></span></div>
<div ng-show="editingData[news.id]"><input type="text" class="form-control" ng-model="news.title" /></div>
</td>
<td>
<div ng-hide="editingData[news.id]"><span ng-bind-html="news | deleteText"></span></div>
<div ng-show="editingData[news.id]"><input type="text" class="form-control" ng-model="news.arg" /></div>
</td>
<td>
<div ng-hide="editingData[news.id]"><input type="checkbox" disabled ng-model="news.isDeleted"></div>
<div ng-show="editingData[news.id]"><input type="checkbox" ng-model="news.isDeleted"></div>
</td>
<td>
<div ng-hide="editingData[news.id]"><button id="modify" class="btn btn-primary" ng-click="modify(news, $event)">Modifica</button></div>
<div ng-show="editingData[news.id]"><button id="accept" class="btn btn-success" ng-click="update(news)">Accetta</button></div>
</td>
<td>
<div ng-hide="editingData[news.id]"><button id="delete" class="btn btn-danger" ng-click="delete(news.id)">Cancella</button></div>
<div ng-show="editingData[news.id]"><button id="cancel" class="btn btn-danger" ng-click="cancelModify()">Annulla</button></div>
</td>
</tr>
</table>
The entry on the table is read from db:
$scope.allNews = function () {
var url = '/data_db.asmx/GetAllNews';
var obj = {};
$http.post(url, obj)
.success(
function (response) {
if (response.Error) {
console.log('Server error');
}
else {
$scope.allNews = response.d;
}
})
.error(
function (response) {
console.log('Unkwnow error.');
});
}
I'd like to highlight the text that is search in the 1st row of the table. For now, i receive this error:
angular.js:13920 Error: [filter:notarray] Expected array but received: function ()
but the filter works.
Your problem is that $scope.allNews is a function. When you use it in ng-repeat directive and the directive is evaluated for the first time, your angular will try to examine the allNews property of your $scope as an array.
When the function gets called the first time (which might never happen when angular first encouters the error), it woul overwrite the allNews property with the resulting array of your $http POST request.
Rename either the function or the property and bind your ng-repeat to the array it recieves (and maybe initialize it with an empty array until it is populated by the $http result).
Something like:
$scope.allNews = [];
$scope.getAllNews = function() {
var url = '/data_db.asmx/GetAllNews';
var obj = {};
$http.post(url, obj)
.success(
function (response) {
if (response.Error) {
console.log('Server error');
}
else {
$scope.allNews = response.d;
}
})
.error(
function (response) {
console.log('Unkwnow error.');
});
}
Alternatively try using ngResource, create a service and inject that into your controller. Then populate the array by accessing the service.
I'm working on site and it has a fram. think of the gmail frame. And much like the gmail app I want only the inner div to be updated when clicking links on the navbar. I've got it so the div changes, but it certainly does not give me the results I'm hoping for. this is a rough outline of what I have
<div id=container>
<div id=page>
... some child divs in here
</div></div>
Because the container has a fixed scroll bar I don't want it to change I want to only replace the page div. this is what I managed to come up with on the jquery side. I'm just a beginner so I don't really know what I'm doing but I'm trying to learn.
$(document).ready(function () {
$.ajaxSetup ({
cache: false
});
var ajax_load = "<img src='bin/pics/loading.gif' alt='loading…' width='32px' height='32px' style='top: 250px; left: 250px;' />";
var loadUrl = "bin/ajax/load.html";
$("#mybuton").click(function(){
$("#page").load(loadUrl);
location.hash = 'ajax';
});
});
the load html contains this
<link rel="stylesheet" type="text/css" href="bin/main.css" />
<div id="page">
<div id="child">
<h1> sometitle </h1>
</div>
</div>
Any suggestions?
Here's the Jquery ajax link http://api.jquery.com/jQuery.ajax/
Eg Code :
ajax_control = jQuery.ajax({
url: "target.php",
type: "POST",
data: {variable_name: variable_value}
});
ajax_control.always(function(){
$('#content').html(ajax_control.responseText);
});
By assigning the call to a variable ("ajax_control" in the above example), you can abort whenever you want, by using :
ajax_control.abort();
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.get/
I don't like to answer with links, nor just text, so here is an example of how can you make a div/table or mostly any html container to change it's content.
If you're using MVC with Razor it'd look like this
TestView.cshtml
#using (Ajax.BeginForm("Test",
"TestController",
new AjaxOptions {
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "searchResults" }))
{
Search User by ID: <input type="text" name="id" />
<input type="submit" value="Search" />
}
<table id="searchResults">
</table>
TestController.cs
public class TestController : Controller
{
public PartialViewResult Test(int id)
{
var model = myDbContext.Users.Single(q => q.UserID == id);
return PartialView("_PartialViewTest", model);
}
}
_PartialViewTest.cshtml
#model IEnumerable<MyApp.Models.User>
<table id="searchResults">
<tr>
<th>Name</th>
<th>Email</th>
</tr>
#foreach(var item in Model) {
<tr>
<td>#item.Name</td>
<td>#item.Email</td>
</tr>
}
</table>
...and if you want to do it using classic ASP.NET, it'd be like this:
TestPage.aspx
<body>
<form id="form1" runat="server">
<div>
<button type="button" onclick='testCall()'>Test!</button>
<hr />
<div id="ajaxResult">
</div>
</div>
</form>
</body>
Scripts.js / TestPage.aspx
function testCall() {
$.ajax({
url: "TestHandler.ashx",
dataType: 'json',
success: callbackTestCall
});
};
function callbackTestCall(payload) {
document.getElementById("ajaxResult").innerHTML = payload;
};
TestHandler.ashx
public class TestHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
Random random = new Random();
string actualData = random.Next(2001).ToString();
context.Response.ContentType = "text/plain";
context.Response.CacheControl = "no-cache";
context.Response.Write(jss.Serialize(actualData));
}
public bool IsReusable
{
// Whether or not the instance can be used for another request
get { return true; }
}
}
If you need further information please, let me know.