Angular $http post with ASP.NET MVC - asp.net-mvc

What am I missing here? I'm trying to pass 2 fields(CustomerID and CompanyName) from my view into my controller. When I put a break point on my controller's action, both custID and Company name are null. I'm sure whatever I'm missing is easy but I'm just not getting into Angular. Any help would be greatly appreciated. Thanks!
HTML
<input type="text" class="form-control" ng-model="new.CustomerID" />
<input type="text" class="form-control" ng-model="new.CompanyName" />
Javascript
$scope.AddCustomer = function () {
debugger;
var urlPost = "/Home/SaveCustomer/";
console.log($scope.new);
alert(urlPost);
$http({
method: 'POST',
url: urlPost,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
data: { custID: $scope.new.CustomerID, CompanyName: $scope.new.CompanyName }
}).success(function() {
alert('Update Successfully!');
});
}
C#
[HttpPost]
public void SaveCustomer(string custID, string CompanyName)
{
}
EDIT
A few weeks after this was posted and an answer was accepted, I found an easier way to accomplish this. Here is a code sample:
HTML
<input type="number" placeholder="CustomerID" ng-model="newCustomer.CustomerID" class="form-control" style="width: 130px" required/>
<input type="text" placeholder="Customer Name" ng-model="newCustomer.CustomerName" class="form-control" style="width: 200px" required />
<input type="text" placeholder="Email" ng-model="newCustomer.CustomerEmail" class="form-control" style="width: 200px" required />
JavaScript
$scope.newCustomer = {
CustomerID: '',
CustomerName: '',
CustomerEmail: ''
};
$scope.addCustomer = function () {
$http.post("/Home/GetCustomer",
{
customerID: $scope.newCustomer.CustomerID,
customerName: $scope.newCustomer.CustomerName,
customerEmail: $scope.newCustomer.CustomerEmail
}).error(function (responseData) {
alert(responseData);
})
.success(function () {
alert('Updated Successfully');
});
C# Controller
[HttpPost]
public void GetCustomer(int customerID, string customerName, string customerEmail)
{
//do something with values
}

I mean your problem is because the binding that web api uses there is base on querystring, so please update your code, I do an example:
public class UsersController : ApiController
{
[HttpPost]
[Route("Users/Save/{custID}/{CompanyName}")]
public string Save(string custID, string CompanyName)
{
return string.Format("{0}-{1}",custID, CompanyName);
}
}
And the html:
<body ng-app="myApp">
<div ng-controller="myController">
<h1>Demo</h1>
<input type="button" value="Save" ng-click="AddCustomer()" />
</div>
<script src="~/Scripts/angular.js"></script>
<script>
var app = angular.module("myApp", []);
app.controller("myController", function($scope, $http) {
$scope.new = {
CustomerID: "CustId1",
CompanyName: "Company 1"
}
$scope.AddCustomer = function () {
var urlPost = "/Users/Save/" + $scope.new.CustomerID + "/" + $scope.new.CompanyName
$http({
method: 'POST',
url: urlPost,
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function () {
alert('Update Successfully!');
});
}
});
</script>
</body>
And if I test:
Regards,

make these changes :
//either define parent object scope only
$scope.new = {}
//or if you want to define child object too . May be to show some default value .
$scope.new = {
CustomerID: '', //empty or may be some default value
CompanyName: ''
}

Related

How to display image in html from function javascript? ASP.NET

halo guys can you help me to display image. How to display image in html from function javascript? ASP.NET
this is my html:
<div class="col-md-4">
<img id="DisplayImage" class="img-responsive thumbnail" width="200" height="200" />
</div>
javascript here =
var DisplayImage = function () {
var file = $("#SelectImage").get(0).files;
var data = new FormData;
data.append("ImageFile", file[0]);
$.ajax({
type: "GET",
url: '/Home/DisplayImage',
data: data,
contentType: false,
processData: false,
success: function (imgID) {
$("#DisplayImage").show();
$("#img_cgv").attr("src", "/UploadImage/" + imgID);
console.log(imgID);
}
})
}
my controller :
[HttpGet]
public ActionResult DisplayImage(int imgid)
{
Models.eCoalDataContext db = new eCoalDataContext();
var img = db.TBL_M_IMAGEs.SingleOrDefault(x => x.ID == imgid);
/*return File("image/jpg");*/
return File(img.IMAGE_TITLE, "image/jpg");
}
I don't have the code about your files, so in my demo I remove it. Below is a work demo to display image in html from function javascript, you can refer to it, hope it can help you.
Besides, in I have e.PNG in UploadImage folder like:
In Controller:
public class DisplayController : Controller
{
public IActionResult Index()
{
return View();
}
public ActionResult DisplayImage(int imgid)
{
imgid = 1;
var Images = new List<Images>()
{ new Images(){ID=1,IMAGE_TITLE="e.PNG"},
new Images(){ID=2,IMAGE_TITLE="flower.PNG"}
};
var img = Images.SingleOrDefault(x => x.Id == imgid);
return Json(img.IMAGE_TITLE);
}
}
Index view:
<input onclick="getA1Rates()" value="Click" type="button"/>
<div class="col-md-4">
<img id="img_cgv" class="img-responsive thumbnail" width="200" height="200" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
function getA1Rates() {
$.ajax({
type: "GET",
url: '/Display/DisplayImage',
contentType: false,
processData: false,
success: function (imgID) {
$("#img_cgv").attr("src", "/UploadImage/" + imgID);
console.log(imgID);
}
})
}
</script>
result:

Select2 custom data return from API

I am working with select2 to display the data return from the API. However, the data didn't manage to load out.Am I doing something wrong? Any ideas how to fix this?
HTML:
<select class="js-example-basic-single form-control select2 select2-hidden-accessible" id="user" name="user_id" autocomplete="off" required="required">
<option value="">Please select</option>
</select>
script:
var url = "{{env('API_URL')}}";
var username = null;
$(".select2").select2({
placeholder: "Please select",
width: null,
ajax: {
dataType: "jsonp",
method: "GET",
data: function (term) {
username = term.term;
return {"username": username};
},
url: url+"user/search/username?",
results: function (data) {
return {
results: data.result.users
};
},
},
formatResult: function (option) {
return "<option value='" + option.id + "'>" + option.username + "</option>";
},
formatSelection: function (option) {
return option.id;
}
});
result return from API:
result : [{"users":["[object] (App\\User: {\"username\":\"Kaki\",\"id\":123456})","[object] (App\\User: {\"username\":\"(Alan)\",\"id\":123457})","[object] (App\\User: {\"username\":\"Alex\",\"id\":123458})","[object] (App\\User: {\"username\":\"Sky\",\"id\":1234569})","[object] (App\\User: {\"username\":\"Kvin\",\"id\":123460})"]}] []
One thing is your JSON return from API who is not well formatted.
[{
"users":[
"[object] (App\\User: {\"username\":\"Kaki\",\"id\":123456})",
"[object] (App\\User: {\"username\":\"(Alan)\",\"id\":123457})",
...
]
}]
should be
[{
"users":[
{"username":"Kaki","id":123456}),
{"username":"(Alan)","id":123457}),
...
]
}]
I don't know what is Select2 version you use, but > 4 is advice.
Use functions templateResult and templateSelection is better, later you can return HTML for nicer rendering.
You can use this snipplet demo.
$(".select2").select2({
placeholder: "Please select",
width: null,
ajax: {
dataType: "json",
method: "GET",
url: function (params) {
// return 'url+"user/search/username?' + params.term;
// Fake url to make demo working, use upper line
return 'http://ip.jsontest.com/';
},
processResults: function (data) {
// Use this function to convert api result to Select2 result
// return {"results":data.users};
// Build fake answer for demo
return {"results":[{"username":"Kaki","id":123456},{"username":"(Alan)","id":123457}]};
},
},
templateResult: function (dataRow) {
if (dataRow.loading) return dataRow.text;
return dataRow.username;
},
templateSelection: function (dataRow) {
return dataRow.username;
}
});
.select2 {
width:50%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/select2/4.0.1/js/select2.full.js"></script>
<select class="form-control select2" id="user_id" name="user_id" autocomplete="off" required="required">
<option value="">Please select</option>
</select>
$(".select2").select2({
placeholder: "Please select",
width: null,
ajax: {
dataType: "json",
method: "GET",
url: function (params) {
// return 'url+"user/search/username?' + params.term;
// Fake url to make demo working, use upper line
return 'http://ip.jsontest.com/';
},
processResults: function (data) {
// Use this function to convert api result to Select2 result
// return {"results":data.users};
// Build fake answer for demo
return {"results":[{"username":"Kaki","id":123456},{"username":"(Alan)","id":123457}]};
},
},
templateResult: function (dataRow) {
if (dataRow.loading) return dataRow.text;
return dataRow.username;
},
templateSelection: function (dataRow) {
return dataRow.username;
}
});
.select2 {
width:50%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/select2/4.0.1/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/select2/4.0.1/js/select2.full.js"></script>
<select class="form-control select2" id="user_id" name="user_id" autocomplete="off" required="required">
<option value="">Please select</option>
</select>

How to stop explorer Json downloading strange bahaviour?

i can not bind Json data to table. Also internet explorer wants to download Json data. How to stop explorer download request and fill table. i have been reading more stackoverflow questions and googling articles. i can not understand why knockout.js cannot bind data. i have been learned binding arhitecture in knockout and json binding.
like That:
http://jsfiddle.net/madcapnmckay/3rRUQ/1/
http://jsfiddle.net/rniemeyer/5EWDG/
i would like to use binding theese methods. but i can not stopping iexplorer downloading behavior.
var result = function () {
$.ajax({
type: "get",
url: "/Contact/GetEmployees/",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
viewModel = ko.mapping.fromJS(data, self.Employees);
},
error: function (error) {
alert(error.status + "<--and--> " + error.statusText);
}
});
};
ko.utils.arrayMap(result, function (i) { Directory.list.push(new Employee(i.EmployeeCode, i.EmployeeName)); });
also :
#{
ViewBag.Title = "GetPerson";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>GetPerson</h2>
<script type="text/javascript">
function Person(FirstName, LastName, Friends) {
var self = this;
self.FirstName = ko.observable(FirstName);
self.LastName = ko.observable(LastName);
self.FullName = ko.computed(function () {
return self.FirstName() + ' ' + self.LastName();
})
self.Friends = ko.observableArray(Friends);
self.AddFriend = function () {
self.Friends.push(new Person('new', 'friend'));
};
self.DeleteFriend = function (friend) {
self.Friends.remove(friend);
};
}
var viewModel = new Person();
$(document).ready(function () {
$.ajax({
url: 'Person/GetPerson',
dataType: 'json',
type: 'GET',
success: function (jsonResult) {
viewModel = ko.mapping.fromJS(jsonResult, mapping);
console.log(viewModel);
ko.applyBindings(viewModel);
}
});
});
var mapping = {
create: function (options) {
var person = options.data,
friends = ko.utils.arrayMap(person.Friends, function (friend) {
return new Person(friend.FirstName, friend.LastName);
});
return new Person(person.FirstName, person.LastName, friends);
}
};
</script>
#using (Html.BeginForm())
{
<p>First name: <input data-bind="value: FirstName" /></p>
<p>Last name: <input data-bind="value: LastName" /></p>
<p>Full name: <span data-bind="text: FullName" /></p>
<p>#Friends: <span data-bind="text: Friends().length" /></p>
#*Allow maximum of 5 friends*#
<p><button data-bind="click: AddFriend, text:'add new friend', enable:Friends().length < 5" /></p>
#*define how friends should be rendered*#
<table data-bind="foreach: Friends">
<tr>
<td>First name: <input data-bind="value: FirstName" /></td>
<td>Last name: <input data-bind="value: LastName" /></td>
<td>Full name: <span data-bind="text: FullName" /></td>
<td><button data-bind="click: function(){ $parent.DeleteFriend($data) }, text:'delete'"/></td>
</tr>
</table>
}
Controller Method:
public class PersonController : Controller
{
//
// GET: /Person/
public ActionResult GetPerson()
{
Person person = new Person
{
FirstName = "My",
LastName = "Name",
Friends = new List<Person>
{
new Person{FirstName = "Friend", LastName="Number1"},
new Person{FirstName = "Friend", LastName="Number2"}
}
};
return Json(person, "text/html", JsonRequestBehavior.AllowGet);
//return Json(person, JsonRequestBehavior.AllowGet); Not working
}
}
How to solve binding and downloading problem?

Jsp ajax call using jquery

I have this code snippet where I am passing data to another jsp file.
Javascript
$(document).ready(function() {
$("#click").click(function() {
name = $("#name").val();
age = $("#age").val();
$.ajax({
type : "POST",
url : "pageTwo.jsp",
data : "name=" + name + "&age=" + age,
success : function(data) {
$("#response").html(data);
}
});
});
});
HTML
<body>
Name:<input type="text" id="name" name="name">
<br /><br />
Age :<input type="text" id="age" name="age">
<br /><br />
<button id="click">Click Me</button>
<div id="response"></div>
</body>
and in pageTwo.jsp, my code is
<%
String name = request.getParameter("name");
String age = request.getParameter("age");
out.println(name + age);
%>
but this is not working.Is any mistake in my Jquery ?.Can any one please help me?.
$("#click").click(function(e) {
// e.preventDefault();
...
return false;
});
and of course install firebug or use chrome default developer tools (f12). open console and run the code.
$(document).ready(function () {
$("#click").click(function () {
name = $("#name").val();
age = $("#age").val();
$.ajax({
type: "POST",
url: "pageTwo.jsp",
data: "{'name':'" + name + "','age':'" + age + "'}",
contentType: "application/json",
async: false,
success: function (data) {
$("#response").html(data.d);
}
});
});
});

How to use flexigrid as a partial view in ASP.NET MVC application?

I am able to display Flexigrid in a normal view called from my main menu. I am using this sample http://mvc4beginner.com/Sample-Code/Insert-Update-Delete/Asp-.Net-MVC-Ajax-Insert-Update-Delete-Using-Flexigrid.html to make it work and it works fine for me.
However, my idea is to use a bit more complex interface - have a regular view with the search controls and on pressing search button show the grid with data for the items I searched.
I tried couple of things so far and can not make it to work. Here is the latest Index view I tried:
#model CardNumbers.Objects.Client
#{
ViewBag.Title = "Clients";
}
<h2>Clients</h2>
<br />
#using (Ajax.BeginForm("Search", "Client",
new AjaxOptions
{
HttpMethod = "POST",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ClientsResults"
}))
{
<fieldset>
<legend>Search</legend>
<label for="clientNo">Client No: </label>
<input type="number" name="searchClientNo" class="numericOnly" /><br />
<label for="clientName">Client Name: </label>
<input type = "text" size =25 data-autocomplete="#Url.Action("QuickSearch", "Client")" name ="searchClientName" />
<div>
<input type="submit" value="Find / Refresh" />
#*<input type="button" value="Find / Refresh" id="ClientsSearch" data-url="#Url.Action("Client", "Client")" />
#*<input type="submit" value="Find / Refresh" />*#
#* #Ajax.ActionLink("Find / Refresh", "Client", new AjaxOptions {UpdateTargetId = "ClientResults",
InsertionMode = InsertionMode.Replace, HttpMethod = "POST"}) *#
#*}*#
</div>
</fieldset>
<div style="padding-left:150px; padding-top:50px; padding-bottom:50px;" id="ClientsResults">
#*#{Html.RenderPartial("_Client", Model); }*#
#*<table id="flexClients" style="display:none"/>*#
</div>
}
#*<br />*#
You can see all the commented attempts here also. So, the Search method in the Clients controller now has this code:
public ActionResult Search(int? searchClientNo = null, string searchClientName = null)
{
// Assume we want to select everything
var clients = Db.Clients; // Should set type of clients to IQueryable<Clients>
if ((searchClientNo ?? 0) != 0) //Number was supplied
clients = clients.Where(c => (c.Number == searchClientNo));
// If clientNo was supplied, clients is now filtered by that. If not, it still has the full list. The following will further filter it.
if (!String.IsNullOrWhiteSpace(searchClientName)) // Part of the name was supplied
clients = clients.Where(c => (c.Name.Contains(searchClientName)));
return PartialView("_ClientsSearch", clients);
//return PartialView("_Client", clients);
}
The commented view is the partial view which has a flexigrid and it's not working. The _ClientsSearch view is the "normal" index view created by using the template and this works.
Do you see what exactly I am missing? The flexigrid method is simply not firing at all when I attempt to use it as a partial view from that main view.
I haven't figured out the more complex scenario I had originally in mind, but I was able to make it work using the regular view. The helpful idea first came from this FAQ:
http://code.google.com/p/flexigrid/wiki/FAQ and also looking a bit closer to that sample I used.
So, now my Client view is this:
#model CardNumbers.Objects.Client
#{
ViewBag.Title = "Client";
}
<form id="frmClientsSearch">
<label for="clientNo">Client No: </label>
<input type="number" name="searchClientNo" class="numericOnly" /><br />
<label for="clientName">Client Name: </label>
<input type = "text" size =25 value ="Please enter the search value"
name ="searchClientName" />
<input type="button" id="btnClientsSearch" value ="Find / Refresh" />
</form>
<div style="padding-left: 150px; padding-top: 50px; padding-bottom: 50px;" id="ClientsResults">
<table id="flexClients" style="display: none">
</table>
</div>
<div style="display: none">
<form id="sform">
<input type="hidden" id="fntype" name="fntype">
<input type="hidden" id="Id" name="Id">
<label for="Number">Client No: </label>
<input type="number" id="Number" name="Number" class="numericOnly" />
<label for="Name">Client Name: </label>
<input type="text" size="25" id="Name" name="Name" /><br />
<label for="Contact11">Contact 1: </label>
<input type="text" size="25" id="Contact1" name="Contact1" /><br />
<div class="float-right">
<button type="Submit" id="btnSave">Submit</button>
<button type=reset id="btnCancel">Cancel</button>
</div>
</form>
</div>
And the main work is done in the .js file (note the AddFormData method):
/// <reference path = "jquery-1.5.1-vsdoc.js"/>
/// <reference path = "jquery-ui-1.8.11.js"/>
$(document).ready(function() {
$(":input[data-autocomplete]").each(function() {
$(this).autocomplete({ source: $(this).attr("data-autocomplete") });
});
});
$(function () {
$('input[name="delete"]').click(function () {
return confirm('Are you sure?');
});
});
$(".numericOnly").keypress(function (e) {
if (String.fromCharCode(e.keyCode).match(/[^0-9]/g)) return false;
});
$("#flexClients").flexigrid({
url: '/Client/Client/',
dataType: 'json',
colModel: [
{ display: 'Client Id', name: 'Id', width: 100, sortable: true, align: 'center', hide: true},
{ display: 'Client #', name: 'Number', width: 100, sortable: true, align: 'center' },
{ display: 'Name', name: 'Name', width: 350, sortable: true, align: 'center' },
{ display: 'Contact 1', name: 'Contact1', width: 350, sortable: true, align: 'center' },
],
buttons: [
{ name: 'Add', bclass: 'add', onpress: test },
{ name: 'Edit', bclass: 'edit', onpress: test },
{ name: 'Delete', bclass: 'delete', onpress: test },
{ separator: true }
],
searchitems: [
{ display: 'Client Name', name: 'Name' }
],
sortname: "Name",
sortorder: "asc",
usepager: true,
title: 'Clients',
useRp: true,
rp: 15,
showTableToggleBtn: true,
width: 1000,
onSubmit: addFormData,
height: 300
});
//This function adds parameters to the post of flexigrid. You can add a verification as well by return to false if you don't want flexigrid to submit
function addFormData() {
//passing a form object to serializeArray will get the valid data from all the objects, but, if the you pass a non-form object, you have to specify the input elements that the data will come from
var dt = $('#sform').serializeArray();
dt = dt.concat($('#frmClientsSearch').serializeArray());
$("#flexClients").flexOptions({ params: dt });
return true;
}
$('#sform').submit(function () {
$('#flexClients').flexOptions({ newp: 1 }).flexReload();
alert("Hello World");
return false;
});
function test(com, grid) {
if (com === 'Delete') {
var clientName = $('.trSelected td:eq(2)').text();
if (clientName) //Variable is defined and not empty
{
if (confirm("Are you sure you want to delete " + $.trim(clientName) + "?"))
return false;
$('#fntype').val('Delete');
$('#Id').val($('.trSelected td:eq(0)').text());
$('#Number').val('');
$('#Name').val('');
$('#Contact1').val('');
$('.trSelected', grid).each(function () {
var id = $(this).attr('id');
id = id.substring(id.lastIndexOf('row') + 3);
addFormData(); $('#flexClients').flexOptions({ url: '/Client/Client/' }).flexReload();
});
clearForm();
}
} else if (com === 'Add') {
$("#sform").dialog({
autoOpen: false,
show: "blind",
width: 1000,
height: 500
});
$("#sform").dialog("open");
$('#fntype').val('Add');
$('#Number').val('');
$('#Name').val('');
$('#Contact1').val('');
} else if (com === 'Edit') {
$('.trSelected', grid).each(function () {
$("#sform").dialog({
autoOpen: false,
show: "blind",
width: 1000,
height: 500
});
$("#sform").dialog("open");
$('#fntype').val('Edit');
$('#Id').val($('.trSelected td:eq(0)').text());
$('#Number').val($('.trSelected td:eq(1)').text());
$('#Name').val($('.trSelected td:eq(2)').text());
$('#Contact1').val($('.trSelected td:eq(3)').text());
});
}
}
function clearForm() {
$("#sform input").val("");
};
$(function () {
$('#btnSave').click(function () {
addFormData();
$('#flexClients').flexOptions({ url: '/Client/Client/' }).flexReload();
clearForm();
$('#sform').dialog('close');
return false;
});
});
$(function () {
$('#btnCancel').click(function () {
// clearForm();
$('#sform').dialog('close');
return false;
});
});
$(function () {
$('#btnClientsSearch').click(function () {
addFormData();
$('#flexClients').flexOptions({ url: '/Client/Client/' }).flexReload();
//$.ajax({
// url: $(this).data('url'),
// type: 'GET',
// cache: false,
// success: function (result) {
// $('#ClientsResults').html(result);
// }
//});
return;//false;
});
});
And my Client method in the controller is the same as it used to be with minor change.
Now, my next challenge is to generalize the above and also somehow instead of calling the form sForm I showed use a more complex form with validations as I if it is from the Create/Edit view.

Resources