Passing form collection with Knockout.js in asp.net MVC - asp.net-mvc-4

I am new to MVC and I am trying to create an application with Knockout.js to send data back to the server dynamically. I am following an example i found at:
http://www.mytecbits.com/microsoft/dot-net/knockout-js-and-bootstrap-with-asp-net-mvc-part-2
It works perfectly off the site, but i am trying to send data to multiple models instead just one as in the example
The Knockout code used in the example to send the data back to the server is
var urlPath = window.location.pathname;
var CreateArticleVM = {
Title: ko.observable(),
Excerpts: ko.observable(),
Content: ko.observable(),
Test: ko.observable(),
btnCreateArticle: function() {
$.ajax({
url: urlPath + '/Create',
type: 'post',
dataType: 'json',
data: ko.toJSON(this),
contentType: 'application/json',
success: function(result) {
window.location.href = urlPath + '/';
},
error: function(err) {
if (err.responseText == "success") {
window.location.href = urlPath + '/';
}
else {
alert(err.responseText);
}
},
complete: function() {}
});
}
};
ko.applyBindings(CreateArticleVM);
How do i modify the above code to be able to accept a FormCollection? Or what is the best solution to my problem?
Thanks

Say your service is expecting more than one argument like following.
[HttpPost]
public String Create(ModelA modela, ModelB modelb)
{
//Server code.
}
In order pass the data for Create method from client side you need to form your postdata as follows.
$.ajax({
url: urlPath + '/Create',
type: 'post',
dataType: 'json',
data: {modela: { "modela data in the expected form" }, modelb : { "modelb data.." } },
contentType: 'application/json',
success: function(result) {
window.location.href = urlPath + '/';
},
.
.
.
.
});

Related

RazorPages return RedirectToPage not working

I've got an odd thing happening. On my index page I've got an ajax call that grabs a parameter off of an SVG and then hits the following code:
public async Task<IActionResult> OnPostStateClickAsync(string state)
{
HttpContext.Session.SetObject("CurrentFilters", SearchFilters);
SearchFilters.State = state;
return RedirectToPage("/Search");
}
I'm able to attach a debugger and see everything is working fine behind the scenes. The problem, the UI doesn't ever update and take me to the Search page. If I manually navigate there all the data is loaded and everything is fine.
Not seen this behavior before and I've used the same code in previous projects.
Here is the AJAX call in case it's relevant:
$(document).ready(function () {
$('path').click(function () {
var stateParameter = $(this).attr('id');
$.ajax({
type: "POST",
url: '/Index?handler=StateClick&state=' + stateParameter,
//data: searchTitle,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
dataType: "json"
}).done(function (data) {
console.log(data.result);
location.reload();
});
});
});
You can change your code like bellow.
Action:
public async Task<IActionResult> OnPostStateClickAsync(string state)
{
//...
return new JsonResult(new { redirectToUrl = "/Search" });
}
In your Ajax:
$(document).ready(function () {
$('path').click(function () {
var stateParameter = $(this).attr('id');
$.ajax({
type: "POST",
url: '/Index?handler=StateClick&state=' + stateParameter,
//data: searchTitle,
contentType: "application/json; charset=utf-8",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
dataType: "json",
success: function (response) {
window.location.href = response.redirectToUrl;
}
});
});
});
Test Result:

Kendo-Vue Datasource.beforeSend issue

i'm using kendovue for an application that i'm creating, the thing is that i must send the bearer token on each request.
but i'm unable to pass it to the server as the function assigned to the beforesend event has the context of the request and not the vue component.
dataSource: new kendo.data.DataSource({
page: 1,
pageSize: 20,
serverPaging: true,
transport: {
read: {
url: "/api/users/list",
dataType: "json",
beforeSend: function (req) {
req.setRequestHeader('Authorization', 'bearer ' + this.$auth.token());
}
}
},
schema: {
total: function (data) {
return data.Data.Total;
},
data: function (data) {
let d = data.Items;
return d;
}
}
}),
can someone point me on the right direction?
regards.
You could define it as method beforeSend: this.beforeSend and add it to the methods collection as below:
methods:{
beforeSend: function (req) {
req.setRequestHeader('Authorization', 'bearer ' + this.$auth.token());
}
}
Here is a sample code that worked correctly at my side: https://stackblitz.com/edit/waonac?file=index.js.

Hapi.js reply.redirect() is not working after image upload

I have the following code, in my server. I'm uploading an image using mongoose and s3 and then want to redirect the user to another page but this isn't happening. (the upload is successful).
Routes.js:
{path: '/success', method: 'GET', config: controller.success} ......
controller.js:
imageUpload: {
payload: {
maxBytes: 209715200,
output: 'file',
parse: true
},
handler: function(request, reply) {
var userName = request.auth.credentials.username;
members.findMemberByUsername(userName, function(err, member){
if (err) {
return reply.view('upload', {error: err});
} else if (member) {
var IDImagePath = request.payload.uploadedIDname.path;
console.log(IDImagePath);
members.addID(member, IDImagePath, function(err1){
console.log("add id error", err1);
if (err1){
return reply.view('upload', {error: err1, member: member});
} else {
console.log("SUCCESSFUL!");
return reply.redirect('/success');
}
});
}
});
}
},
success: {
handler: function (request, reply){
request.auth.session.clear();
console.log("success handler working!!");
return reply.view('success');
}
}
The code hits both console.log("SUCCESSFUL") and console.log("success handler working!!") in the controller but the redirect doesn't take place. By the way I'm using 'Jade' as the templating language so I have a success.jade. Thanks.
I found out what the problem was. I'm using AJAX on the client side but didn't have a 'success' method to reload the page:
$('#submitID').click(function(){
var formData = new FormData($('#uploadID')[0]);
$.ajax({
url: '/api/image',
type: 'POST',
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
console.log(myXhr.upload);
}
return myXhr;
},
success: function(data) {
window.location.href = "/success"
},
data: formData,
cache: false,
contentType: false,
processData: false
}, "json");
});
I needed window.location.href = "/success" to reload the page. Please note the jQuery Ajax SUCCESS method is different to my '/success' route, they just happen to be the same word.

what's wrong when using jquery to call wcf service, always return internal server error?

Below is my jquery codes, and it always return internal server error, and i'm sure that my wcf service can be called from i.e and iis.
$.support.cors = true;
$.ajax({
type: "post",
url:"http://localhost:8080/WcfService/FunHeartWork.svc/UpdateMedia",
data: '{"desc":"' + text + '","albumId":"'+albumId+'","mediaId":"'+mediaId+'","userName":"'+userName+'"}',
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (result) {
alert(result);
},
error:function(a,b,c){alert(c);},
failure: function (msg) {
alert(msg);
}
});
Try changing the data line to:
data: {
desc: text,
albumId: albumId,
mediaId: mediaId,
userName: userName
},

how to call this calling WCF method continuously

I have an ajax enabled WCF service method :
[OperationContract]
public string Test(string name)
{ return "testing testing." + name; }
and I am calling it with following code:
$(document).ready(function () {
var varData = $("#NewSkill").val();
$("#Button1").click(function () {
$.ajax({
type: "POST",
url: "TimeService.svc/Test",
data: '{"name" : "John"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);
}
});
});
});
I want to call this method continuously after every 5 seconds using above code . How can I do this ?
Move the $.ajax(); part to a Javascript function say AjaxCall(). Create a javascript variable
var isActivated = false;
$(document).ready(function () {
while(isActivated){
setTimeout("AjaxCall()",3000);
}
}
);
$("#Button1").click(isActivated = true)
Hope this helsps...