This is my model file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ConsumeJson.Models
{
public class ProductModel
{
public List<Product> findAll()
{
List<Product> result = new List<Product>();
result.Add(new Product { Id = "p01", Name = "Product 1", Price = "100", Quantity = "1" });
result.Add(new Product { Id = "p02", Name = "Product 2", Price = "200", Quantity = "2" });
result.Add(new Product { Id = "p03", Name = "Product 3", Price = "300", Quantity = "3" });
return result;
}
public Product find(string id)
{
return findAll().Single(p => p.Id.Equals(id));
}
}
}
This is my HTML file.
<!DOCTYPE html>
<html ng-app="myapp">
<head>
<meta charset="utf-8" />
<script src="Scripts/jquery-3.3.1.min.js"></script>
<script src="Scripts/jquery-3.3.1.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.7.2/angular.min.js"></script>
<title>My Client</title>
</head>
<body ng-controller="productController">
<table cellpadding="2" cellspacing="2" border="1">
<tr>
<th>Id</th>
<th>Name</th>
</tr>
<tr ng-repeat="product in result">
<td>{{product.Id}}</td>
<td>{{product.Name}}</td>
</tr>
</table>
<script type="text/javascript">
var myapp = angular.module('myapp', []);
myapp.controller('productController', function ($scope, $http) {
$http(
method: 'GET',
url:'http://localhost:53204/api/product').success(function (response) {
$scope.result = response;
})
})
</script>
</body>
</html>
I want to create product's table with informations but hen i run it as localhost it never display the product's id or name.
It stays like this way. {{Product.Id}} {{Product.Name}} How can i solve this?
You need to change it to using .then()
$http({
method: "GET",
url: "http://localhost:53204/api/product"
}).then(function mySucces(response) {
$scope.result = response.data;
}, function myError(response) {
});
May have many reason.
Check your scope inserted, are you sure that you send ProductId to server side with Http request?.
it's better that use of ngModel instead of dubble braces. check this
and the Important issue is, if your model like this:
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
public string PhoneNumber { get; set; }
}
when your API wants to return your response, convert data to Json, attention that your model is KebabCase but your Json in camelCase, but in your html you use of KebabCase.
If all of this issues not work, check your network and check response of your request in response tab, Is there any response or any Ids?
GoodLuck.
Related
I am trying to store the employeeIds from the selected row of the table into the model column EmployeeReinstateVM.selectedEmployeeId from the click event of 'btnUpdate', each id must be stored to EmployeeReinstateVM.selectedEmployeeId. Currently the Ids are stored in to selectedEmployeeId hidden column as array string "23,24,25" So I am trying to store each employee id of the selected rows into the EmployeeReinstateVM.selectedEmployeeId from javascript to send the model into controller post method with selected employeeIds. I am looking for the help from someone. Here is the code
Model Class
public class EmployeeReinstateVM
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public List<string> selectedEmployeeId { get; set; }
public IEnumerable<EmployeeModel> employees { get; set; }
}
Views
<style>
.selectable-row.selected {
background-color: #ddd;
}
</style>
#model EmployeeReinstateVM
foreach (var item in Model.employees)
{
<tr class="selectable-row
#(Model.selectedEmployeeId.Contains(item.EmployeeID.ToString()) ? "selected" :"")"
employee-id="#item.EmployeeID">
<td>#item.EmployeeID</td>
<td>#item.EmployeeName</td>
</tr>
}
<input hidden id="selectedEmployeeId" asp-for="selectedEmployeeId" name="selectedEmployeeId" value="">
<button type="submit" class="btn btn-primary form-control" id="btnUpdate" name="btnActivate" value="update">
Update
</button>
<script type="text/javascript">
$(document).ready(function() {
var employeeIds = [];
$(".selectable-row").click(function() {
$(this).toggleClass("selected");
var employeeId = $(this).attr('employee-id');
if ($(this).hasClass("selected")) {
employeeIds.push(employeeId);
//employeeIds.push($(this).attr('employee-id'));
} else {
employeeIds = employeeIds.filter(function(id) {
return id !== employeeId;
});
}
});
$("#btnUpdate").click(function() {
$("#selectedEmployeeId").val(employeeIds);
console.log($("#selectedEmployeeId").val());
});
})
This seems to be simpler - you need to store the result
$(".selectable-row").click(function() {
$(this).toggleClass("selected");
$("#selectedEmployeeId")
.val(
$("tr[employee-id].selected")
.map(function() { return $(this).attr("employee-id") })
.get()
.join(",")
);
});
store each employee id of the selected rows into the
EmployeeReinstateVM.selectedEmployeeId from javascript to send the
model into controller post method with selected employeeIds
Do you want to try the below code?
$("#btnSave").click(function () {
$("#selectedEmployeeId").val(employeeIds);
console.log($("#selectedEmployeeId").val());
$.ajax({
type: "POST",
url: "/Keepselected/ReinstateEmployee",
data: { "selectedEmployeeId": employeeIds },
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (response) {
alert(response);
}
});
});
result:
Newbie ALERT
Basically I have a web application that has a dropdown list. When you select an item in the drop-down list the table is drawn to show all the credentials that are tied to that drop-down option.
Problem: When running, everything functions properly except for the JavaScript piece that does not remove the line in the table, but deletes the record on the back-end. So once i refresh and go back to that credential type the one I deleted is gone.
I've tried a lot of different stuff, but i pretty new to JavaScript and C#, don't know if there is a better way of doing this. Probably supplied too much information but i rather too much than not enough! :)
Any help, tips, ideas are greatly appreciated.
Credential API Controller: Delete Function
[HttpDelete]
public IHttpActionResult DeleteCustomer(int id)
{
var credentialInDb = _context.Credentials.SingleOrDefault(c => c.Id == id);
if (credentialInDb == null)
return NotFound();
_context.Credentials.Remove(credentialInDb);
_context.SaveChanges();
return Ok();
}
Model for Credential
public class Credentials
{
public int Id { get; set; }
[Required]
[StringLength(255)]
public string Name { get; set; }
[Required]
[StringLength(255)]
public string Username { get; set; }
[Required]
[StringLength(255)]
public string Password { get; set; }
public string Website { get; set; }
public string Notes { get; set; }
public CredentialType CredentialType { get; set; }
[Display(Name = "Credential Type")]
public int CredentialTypeId { get; set; }
}
ViewModel for CredentialFormViewModel
This allows the selectedCredential variable for the page below
public class CredentialFormViewModel
{
public IEnumerable<CredentialType> CredentialTypes { get; set; }
public Credentials Credentials { get; set; }
public int SelectedCredentialTypeId { get; set; }
}
View that displays the DataTable:
#model Appp.ViewModels.CredentialFormViewModel
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Select a Credential Type</h2>
#Html.DropDownListFor(m => m.SelectedCredentialTypeId, new SelectList(Model.CredentialTypes, "Id", "Name"), "Select Credential Type", new { #class = "form-control", onchange = "SelectCredType()" })
<br/>
<table id="credentials" class="table table-bordered table-hover">
<thead>
<tr>
<th>Credential</th>
<th>Username</th>
<th>Password</th>
<th>Website</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
#section scripts
{
<script>
function SelectCredType() {
var credId = $('#SelectedCredentialTypeId').val();
if ($.fn.dataTable.isDataTable("#credentials")) {
if (credId == "") {
var table = $("#credentials").DataTable();
table.destroy();
} else {
var table = $("#credentials").DataTable();
table.destroy();
SelectCredType();
}
} else {
$(document)
.ready(function() {
var table = $("#credentials")
.DataTable({
ajax: {
url: "/api/credentials?credentialTypeId=" + credId,
dataSrc: ""
},
columns: [
{
data: "name",
},
{
data: "username"
},
{
data: "password"
},
{
data: "website"
},
{
data: "id",
render: function(data, type, credentials) {
return "<button class='btn btn-primary btn-xs js-delete' data-credential-id=" + credentials.id + ">Delete</button>";
}
}
]
});
}
);
}
};
$("#credentials")
.on("click",
".js-delete",
function() {
var button = $(this);
bootbox.confirm("Are you sure you want to delete this?",
function(result) {
if (result) {
$.ajax({
url: "/api/Credentials/" + button.attr("data-credential-id"),
method: "DELETE",
sucess: function() {
table.row(button.parents("tr")).remove().draw();
}
});
}
});
});
</script>
}
First issue
Your JavaScript code does not work because the table variable is undefined within your delete function.
There are many ways you could approach to fix that. But first you will need to get your head around variable scopes in JavaScript.
Your simplest solution is to make table a globally-scoped variable that way you can access the instance from any function you create. So instead of defining it here:
...
$(document)
.ready(function() {
var table = $("#credentials")
...
Move it up to the top of your script file:
var table;
function SelectCredType() {
...
$(document)
.ready(function() {
table = $("#credentials")
...
}
Now when you access it from your Delete function, it will be defined.
Note: I would also change the name of the table variable to something else as global variables in JavaScript will conflict with any script you import which can lead to a debugging nightmare. Best to name it something that will be most likely unique, eg. coberlinTable.
Second Issue
I don't know if you did a cut and past error, but you have misspelled success in your ajax Delete function.
I am attempting to using knockout to create a client side model so client side validation can be done on the needed attributes, some of which are nested and or in nested lists of other models.
In following some guides and patterns, I have tried to map a test list from the main view model and send it back to the controller when the form submits, with validation that would prevent the form from being submitted if the value is null.
When the form is submitted, not only does it fail to validate with the current set up, the edited values (which are correctly populated in the view on load, so some type of binding is correctly working) return as null in the controller.
namespace KnockoutDemo.Models
{
public class XmlParameter
{
public HttpPostedFileBase XmlValue;
public string Name;
}
}
public class TestStepViewModel
{
public int TestStepId { get; set; }
public string TestStepName { get; set; }
public string Message { get; set; }
public List<XmlParameter> XmlParameters { get; set; }
}
View
#using System.Web.Mvc.Ajax
#using System.Activities.Expressions
#using System.Web.Script.Serialization
#model KnockoutDemo.Models.TestStepViewModel
#{ string data = new JavaScriptSerializer().Serialize(Model);}
#section scripts
{
<script src="~/Scripts/knockout-3.4.0.js"></script>
<script src="~/Scripts/knockout.mapping-latest.js"></script>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/teststepviewmodel.js"></script>
<script type="text/javascript">
var testStepViewModel = new TestStepViewModel(#Html.Raw(data));
ko.applyBindings(testStepViewModel);
</script>
}
<form>
<div>
<div class="form-group">
<label class="control-label" for="TestStepName">Test Step Name:</label>
<input class="form-control" name="TestStepName" id="TestStepName" data-bind="value: TestStepName"/>
</div>
<div class="form-group">
<label class="control-label" for="TestStepName">Test Step Id:</label>
<input class="form-control" name="TestStepId" id="TestStepId" data-bind="value: TestStepId" disabled="disabled"/>
</div>
<table class="table table-striped">
<tr>
<th>Product Code</th>
</tr>
<tbody data-bind="foreach: XmlParameters">
<tr>
<td class="form-group"><input name="Name" class="form-control input-sm" data-bind="attr: {'id': 'Name_' + $index()}, value: Name"/></td>
</tr>
</tbody>
</table>
</div>
<p><button class="btn btn-primary" data-bind="click: save" type="submit" >Save</button></p>
</form>
teststepviewmodel.js + validation
TestStepViewModel = function(data) {
var self = this;
ko.mapping.fromJS(data, {}, self);
self.save = function () {
$.ajax({
url: "/Home/Save/",
type: "POST",
data: ko.toJSON(self),
contentType: "application/json"
});
}
}
var XmlParameter = function(data) {
var self = this;
ko.mapping.fromJS(data, mapping, self);
}
var mapping = {
'XmlParameters': {
key: function (xmlParameters) {
return ko.utils.unwrapObservable(xmlParameters.Name);
},
create: function (options) {
return new XmlParameter(options.data);
}
}
};
$("form").validate({
submithandler: function () {
testStepViewModel.save();
},
rules: {
TestStepName: {
required: true,
maxlength: 30
},
Value: {
required: true
},
XmlValue: {
required: true
}
},
messages: {
TestStepName: {
required: "A Test Step must have a non-null value, please enter a name"
},
Value: {
required: "The parameter can't be null/empty"
}
}
});
The JsonResult Save() controller correctly populates the Id and Test Step Name, however the XmlParameters are both null.
Controllers (Like I said, this is simply a test to return knockout model with client side validation, so I'm simply populating a view model on load and setting a breakpoint on the JsonResult to see the contents of the model)
public ActionResult Index(TestStepViewModel ts)
{
TestStepViewModel testStepViewModel = new TestStepViewModel
{
TestStepName = "Editing A Test Step",
TestStepId = 10,
Message = "Hello, this is a message"
};
testStepViewModel.XmlParameters = new List<XmlParameter>();
testStepViewModel.XmlParameters.Add(new XmlParameter
{
Name = "Xml P1"
});
testStepViewModel.XmlParameters.Add(new XmlParameter
{
Name = "Xml P2"
});
return View("Index", testStepViewModel);
}
public JsonResult Save(TestStepViewModel testStepViewModel)
{
return null;
}
Hi I am working with mvc4
I have a razor view page for the action
public ActionResult DeliveryAddress(string userid,int productid)
{
....
return View(m);
}
that contain
<div >DELIVER HERE</div>
when clicking on this i am collecting somedata ifrom this page using jquery,
$(document).ready(function () {
$("#place-order").click(function () {
var userid = $('#selected-userId').html();
var productid = $('#selected-productId').html();
$.get("Products/PlaceOrder/"+ userid, function (data) { });
});
});
and i want to pen another view of action
[HttpGet]
public ActionResult PlaceOrder(int uid)
{
return View();
}
and paste the variable content,
but $.get("Products/PlaceOrder", function (data) { }); is not hitting this action..
please help me.
This is how you need to pass a data to a url in Jquery get method, note the same parameter name is used in the function
$.get('#Url.Action("PlaceOrder","Products")', { uid: userid }, function (data)
{
});
Make sure your URL is correct. Most probably use #Url.Action(). and also pass the parameter using new as shown below.
$.get('#Url.Action("PlaceOrder","Products",new { userid = #userid , productid = #productid })', function (data) {
});
While collecting the data make sure your parameter names are same for both while sending and while receiving.
[HttpGet]
public ActionResult PlaceOrder(int userid, int productid )
{
return View();
}
Just add HTTPGET attribute in your action method as below.
[HttpGet]
public ActionResult PlaceOrder()
{
return View();
}
java script
$("#place-order").click(function () {
var userid = $('#selected-userId').html(); // $('#selected-userId').val();
$.get('#Url.Action("PlaceOrder","Products", new { uid = userid })', function (data) { });
var productid = $('#selected-productId').html();
});
When I want my view code to be fetched like that, or even through the Html.Action() call, I use the PartialView and normally set my Controller Action as:
public ActionResult PlaceOrder(int uid)
{
return PartialView(new TestViewModel() { ID = uid });
}
as an example:
TestViewModel
public class TestViewModel
{
public int ID { get; set; }
}
PlaceOrder.cshtml
#model TestViewModel
<h2>Partial View</h2>
<p>
Partial View paragraph with the id <b>#Model.ID</b>
</p>
Index.html
<hr />
#Html.Action("PartialView", "Home", new { id = 44 })
<hr />
<div class="ap"></div>
<script>
var url = '#Url.Action("PartialView", "Home")';
$.get(url, { id: 54 }, function (data) {
$(".ap").append(data);
});
</script>
result:
To preface this question, I will admit that I know nothing about javascript and related topics. I am trying to have a table be created and filled out based on a button push. If I pass the data directly into the ViewModel, it displays correctly, so I know the table is working right. Here is the JQuery request:
<input type="button" id="RootsBtn" value="Go"/>
<script language="javascript" type="text/javascript">
$(function () {
$("#RootsBtn").click(function () {
$.ajax({
cache: false,
type: "GET",
url: "#(Url.RouteUrl("GetApplications"))",
data: {},
success: function (data) {
alert(data.length);
$('#AppTableID').show();
},
error: function (xhr, ajaxOptions, throwError) {
alert("Error");
$('#AppTableID').hide();
}
});
});
});
</script>
I'm basing this code loosely on code I'm using to populate a dropdown list. I know the data is being grabbed properly because the alert(data.length); line shows the proper number of objects in my list.
The dropdown code included a $.each line. I have tried using variants of this and nothing has worked for me.
How would I get the data saved into my ViewModel so that it can be displayed?
EDIT: Adding more details
This is the Table display in my view:
<div id="AppTableID">
<table id="dashboard">
<thead>
<th>
#Html.LabelFor(model => model.apps.FirstOrDefault().AppStringID)
</th>
<th>
#Html.LabelFor(model => model.apps.FirstOrDefault().ApplicationCategoryID)
</th>
<th>
#Html.LabelFor(model => model.apps.FirstOrDefault().Description)
</th>
</thead>
#foreach (var item in Model.apps ?? new List<Application> { null })
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.AppStringID)
</td>
<td>
#Html.DisplayFor(modelItem => item.ApplicationCategoryID)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
</tr>
}
</table>
</div>
This is my viewmodel which is passed into the view:
public class HomeViewModel
{
public HomeViewModel()
{
apps = new List<Application>();
}
public IEnumerable<Application> apps { get; set; }
}
This is the Application class:
public class Application
{
public long ID { get; set; }
public string AppStringID { get; set; }
public int? ApplicationCategoryID { get; set; }
public string Description { get; set; }
}
This is GetApplications: (appService.ToList() correctly gets the list of data. This has been well tested.)
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetApplications()
{
var apps = appService.ToList();
if (apps == null)
{
return Json(null, JsonRequestBehavior.AllowGet);
}
return Json(apps, JsonRequestBehavior.AllowGet);
}
In the success function of your ajax call
$.ajax({
....
success: function (data) {
$.each(data, function(index, item) {
var row = $('<tr></tr>'); // create new table row
row.append($('<td></td>').text(item.AppStringID));
row.append($('<td></td>').text(item.ApplicationCategoryID));
row.append($('<td></td>').text(item.Description));
$('#dashboard').append(row); // add to table
});
$('#AppTableID').show();
},
....
});
Notes: You should probably include a tbody element as a child of your table and add the rows to that. Your foreach loop only needs to be #foreach (var item in Model.apps) {.. (the collection has been initialized in the constructor). You also don't need the if (apps == null) {..} condition in the GetApplications method