how to pass knockoutjs view model into a mvc controller - asp.net-mvc

I have the following function in a MVC controller
public class XyzController:Controller
{
public ActionResult Index(){...}
[HttpPost]
public bool Save(string jsondata)
{
//parse json data to insert into the database
}
}
I want to pass this view model into the Save function
var myObj = function (id) {
var self = this;
self.myId = id;
self.parameters = ko.observableArray();
}
var ViewModel = function () {
var self = this;
self.myObjList = ko.observableArray();
self.sendItems = function() {
$.ajax({
type: "POST",
url: '/Xyz/Save',
data: ko.toJSON(self),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
},
error: function (request, status, error) {
alert(request.statusText);
}
});
}
}
var vm = new ViewModel()
ko.applyBindings(vm);
I do get the data if I pass the data as JSON.stringify({jsondata:ko.toJSON(self)}), but how do I then convert it into a object so that I can iterate over the myObjList and the parameters?

First of all try changing your Model to something like this :-
[JsonObject(MemberSerialization.OptIn)]
public class Test
{
[JsonProperty("myId")]
public string Id { get; set; }
[JsonProperty("parameters")]
public List<string> Parameters { get; set; }//List<string> or whatever it takes int of string
}
if it doesn't work, the please post your Ajax request data... Else....
I follow approach like this:-
MODEL:-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Newtonsoft.Json;
namespace MvcApplication4.Models
{
[JsonObject(MemberSerialization.OptIn)]
public class Test
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
}
}
CONTROLLER
//
// POST: /Testing/
[HttpPost]
public void Post(MvcApplication4.Models.Test request)
{
try
{
//DO YOUR STUFF
}
catch (Exception ex)
{
throw (ex);
}
}
AJAX Call:-
var json = {};
json = data.id;
json = data.name;
$.ajax({
type: "POST",
url: ""//Your URL,
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: ko.toJSON(json)
}).done(function (data) {
}).fail(function (request, error) {
});
OR make your AJAX call like
$.ajax({
type: "POST",
url: ""//Your URL,
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: ko.toJSON({ id: value1, name: value2 }),//Get value1 and value2 from you ko varables
}).done(function (data) {
}).fail(function (request, error) {
});

Related

Why this ajax post request does not work in mvc app

i have js file with ajax request
this is part of its text
$.ajax({
url: '/Points/Addpoint', // также '#Url.Action("Addpoint", "PointsController")'
type: "POST",
dataType: "json",
data: JSON.stringify({ firstx: ev._x, firsty: ev._y, secondx: ev._x, secondy: ev._y }),
success: function () {
alert();
}
});
i also have mvc controller with this method which should be called in ajax
[HttpPost]
public void Addpoint(JSON po)
{
var pointslist = this.Getpoints();
var obj = po;
pointslist.Add(new Point());
}
But somehow this doesnt work. idk why?it gives me 500 error and message
There are no parameterless constructors defined for this object.
what should i do to solve this problem and send this json obj?
Change the JSON to class and change your post
public class YourClass
{
public string firstx { get; set; }
public string firsty { get; set; }
public string secondx { get; set; }
public string secondy { get; set; }
}
[HttpPost]
public void Addpoint([FromBody] YourClass po)
{
var pointslist = this.Getpoints();
var obj = po;
pointslist.Add(new Point());
}
$.ajax({
url: '/Points/Addpoint',
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ firstx: ev._x, firsty: ev._y, secondx:ev._x,secondy: ev._y }),
success: function () {
}
});

500 error Sending JSON to Controller MVC

I am trying to send JSON data to the controller and use the data to modify the database.
This is my ajax call:
var ajaxresult = [];
var table = $('<table>').addClass('table ');
$('button').on('click', function () {
$.ajax({
headers: {
"Content-Type": "application/json",
"Accept": "application/json"
},
type: 'GET',
url: 'https://api.github.com/search/repositories?q=repos+topic:' + $(this).attr('id') + '&sort=stars&order=desc&per_page=10',
success: function (data) {
ajaxresult.push(data);
debugger;
table.empty();
table.append("<thead><tr><th>Avatar</th><th>Name</th><th>Score</th><th>URL</th><th>Updated at</th></tr></thead>");
$.each(data.items, function (i, object) {
var row = $('<tr>').addClass('table-primary');
row.append('<td><img src=' + object.owner.avatar_url + 'height=50px width=50px/></td>');
row.append('<td>' + object.name + '</td>' + '<td>' + object.score + '</td>' + '<td>' + object.url + '</td>' + '<td>' + object.updated_at + '</td>');
table.append(row);
});
table.append('</table>');
$('table').replaceWith(table);
}
});
});
$('#save').on('click', function () {
debugger;
$.ajax({
contentType: 'application/json; charset=utf-8',
dataType: 'json',
type: 'POST',
url: 'http://localhost:60294/Git/Updateto',
data: ajaxresult,
success: function (data) {
alert('done');
},
error: function (data) {
alert('error');
}
});
});
This is the controller to which I am trying to POST the data:
[HttpPost]
public async Task<IActionResult> Updateto(List<gitd> obj,gitd gitd )
{
if (ModelState.IsValid)
{
foreach (var item in obj)
{
item.AvatarURL = gitd.AvatarURL;
item.Name = gitd.Name;
item.Score = gitd.Score;
item.Updatedat = gitd.Updatedat;
}
await _context.SaveChangesAsync();
}
return View(gitd);
}
}
This is the model which I want to use and save data to the database:
public class gitd
{
public int ID { get; set; }
public string AvatarURL { get; set; }
public string Name { get; set; }
public decimal Score { get; set; }
public DateTime Updatedat { get; set; }
}
I am getting a 500 Internal error, when I looked using the debugger, whenever the POST request is called. the control moves directly to the close of the ajax function. In the JQUERY XML, I could see that data is undefined and handleobj is undefined and all the post data becomes NULL.How do I resolve this?
As ajaxresult is a global variable,shoudl not the json data be there in the #save button ajax call?Why is the data NULL.
I also tried giving data inside the POST request as:
data:{
"name":"John",
"age":30,
"cars":[ "Ford", "BMW", "Fiat" ]
}
but still the error persists.

image browser imageBrowser_listUrl not working

i have tried to get the plugin Image-Browser to work, but i cant figure out, what im missing here.
im using this class:
public class GetImagesToJsonClass
{
public string image { get; set; }
public string thumb { get; set; }
public string folder { get; set; }
}
and this JsonResult
public JsonResult GetFiles()
{
List<GetImagesToJsonClass> GetFiles = new List<GetImagesToJsonClass>();
DirectoryInfo GetDIR = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath("~/Content/Images/"));
foreach (FileInfo item in GetDIR.GetFiles())
{
GetImagesToJsonClass NewFile = new GetImagesToJsonClass();
NewFile.image = string.Format("/Content/Images/{0}", item.Name);
NewFile.thumb = string.Format("/Content/Images/{0}", item.Name);
NewFile.folder = "Test";
GetFiles.Add(NewFile);
}
string GetJson = JsonConvert.SerializeObject(GetFiles);
return Json(GetJson, JsonRequestBehavior.AllowGet);
}
using this on a "test" site
<script>
var myURL = '#Url.Action("GetFiles", "Sales")';
var Getfiles = $.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: myURL,
data: "",
datatype: "Json",
});
Getfiles.done(function () {
try {
var tempdata = (Getfiles.responseText);
var data = JSON.parse(tempdata);
document.write(data);
}
catch (e) {
alert("fejl:" + e);
}
});</script>
and the output is:
[{"image":"/Content/Images/testimage2.jpg","thumb":"/Content/Images/testimage2.jpg","folder":"Test"}]
and ofc this to activat it
CKEDITOR.replace('editor1', {
"extraPlugins": 'imagebrowser',
"imageBrowser_listUrl": "/Sales/Test"
});
And get an error
parsererror: invalid JSON file: "/Sales/Test/": Unexpected token <
and if i set the feed directly in i get a [object, object] error?
what am i doing wrong here?

observableArray sent as parameter to a contoller function is null

I want to pass the data in the FeatureList (observableArray) to the SaveMappings function in the TreeController. I have binded a button to the sendItems function. I put a breakpoint at the var data=p2fData line to see what I received. p2fData is null.
I changed the controller to public JsonResult SaveMappings(List p2fData). In this case p2f data shows that there is 1 element, but then its null too.
var Feature = function (featId) {
var self = this;
self.featId = featId;
self.parameters = ko.observableArray();
}
var ParameterToFeatureListViewModel = function () {
var self = this;
var newFeature = new Feature("Feature XYZ");
newFeature.parameters.push("1");
newFeature.parameters.push("2");
self.FeatureList = ko.observableArray([newFeature]);
self.sendItems = function() {
$.ajax({
type: "POST",
url: '/Tree/SaveMappings',
data: ko.toJSON(self.FeatureList),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response);
},
error: function (request, status, error) {
alert(request.statusText);
}
});
}
}
var vm = new ParameterToFeatureListViewModel()
ko.applyBindings(vm);
public class TreeController:Controller
{
public ActionResult Index(){...}
[HttpPost]
public JsonResult SaveMappings(string p2fData)
{
var data = p2fData;
return Json(data);
}
}
Please have a look # how to pass knockoutjs view model into a mvc controller
... May be it helps..

Pass raw html from view to controller

I want to pass raw html from view to controller. Iam trying to do it with jquery ajax request. Everything is ok until object with raw html passes to controller. What is my mistake?
Here is my model, controller and jquery.
Thank you.
Model
public class NewsEditionModel
{
public string Title { get; set; }
public string SubTitle { get; set; }
public string Text { get; set; }
}
Controller
public ActionResult AddText(NewsEditionModel obj)
{
var news = new News();
try
{
news.Text = obj.Text;
news.PublishDate = DateTime.Now;
news.Title = obj.Title;
var repository = new Repository();
var success = repository.AddNews(news, User.Identity.Name);
return Json(new {data = success});
}
catch (Exception)
{
return View("Error");
}
}
Jquery
function submitForm() {
var text = ste.getContent();
var title = $('#title').val();
var obj1 = JSON.stringify({ Text: text, Title: title, SubTitle: "" });
var obj = $.parseJSON(obj1);
$.ajax({
type: "POST",
dataType: "json",
content: "application/json",
data: {obj: obj},
url: '#Url.Action("AddText", "News")',
success: function (res) {
}
});
}
Just add <ValidateInput(False)> _ to your contoller post req.
You can use this example
$.ajax({
url: '#Url.Action("AddText", "News")',
data: {obj: JSON.stringify({ Text: text, Title: title, SubTitle: "" })},
contentType: 'application/json',
dataType: 'json',
success: function (data) { alert(data); }
});
I guess instead of this:
data: {obj: obj},
you should do it like this:
data: {obj: JSON.stringify({ Text: text, Title: title, SubTitle: "" })},

Resources