MVC3 Ajax Get String and post it back - ajax

on MVC3 Page load i have a String in a Model which is should be the JSONObj.
private string CreateJSONObj(Model model)
{ return "{ name: 'test', Items: [{ test: 1 }, { test: 2 }]"; }
Model.jsonModel = CreateJSONObj(model);
Now i want to implement it in my page:
<script>var jsModel = eval('#Model.jsonModel');
var jsonModel = $.toJSON(jsModel);
$.ajax({
url: 'Page/SetJSON/',
type: "POST",
data: jsonModel,
datatype: "json",
contentType: "application/json; charset=utf-8",
success: function () {
$('#test').html('Saved').fadeIn(),
},
error: function () {
$("#test").html("error"),
}
});</script>
But the Controller gets a null Object. If i write the jsonstring into the script everthing is fine.
Should i use eval? But var jsModel = eval('#Model.jsonModel'); has no effect. What is wrong? :-)

You don't need to use a CreateJSONObj method or a jsonModel property on your model. In order to use it in the view you could simply use the JavaScriptSerializer class which will convert the server side model object into a javascript object:
<script type="text/javascript">
var jsModel = #Html.Raw(new JavaScriptSerializer().Serialize(Model));
$.ajax({
url: '#Url.Action("SetJSON", "Page")',
type: 'POST',
data: JSON.stringify(jsModel),
contentType: 'application/json; charset=utf-8',
success: function () {
$('#test').html('Saved').fadeIn();
},
error: function () {
$('#test').html('error');
}
});
</script>
This will successfully send the model to the following controller action:
[HttpPost]
public ActionResult SetJSON(Model model)
{
...
}
where the Model class contains all the necessary information:
public class Model
{
public string Name { get; set; }
public IEnumerable<Item> Items { get; set; }
}
public class Item
{
public int Test { get; set; }
}
and the controller:
public class PageController: Controller
{
// Used to render the view
public class Index()
{
var model = new Model
{
Name = "Test",
Items = new[]
{
new Item { Test = 1 },
new Item { Test = 2 },
}
};
return View(model);
}
// Used to handle the AJAX POST request
[HttpPost]
public ActionResult SetJSON(Model model)
{
...
}
}

Related

value is not pass from view to controller using ajax

I am performing an AJAX call using a function but my value did not pass through it.
function GoToUpdatePage(currentID) {
var SessionTegInfo = {};
SessionTegInfo.StockCode = document.getElementById("stocktxt").checked;
SessionTegInfo.StockCodeValue = document.getElementById("SearchValuestock").value;
SessionTegInfo.CurrentID = currentID;
$.ajax({
url: "#Url.Action("UpdateWithSessionStore", "MyMasterUpdate")",
data: JSON.stringify(SessionTegInfo),
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
},
error: function (data) {
}
});
}
Here is my code from server side
[HttpPost]
public IActionResult UpdateWithSessionStore([FromBody] MySessionClass SessionTegInfo)
{
.....
return RedirectToAction("Index", "MyUpdateController", new { id = SessionTegInfo.CurrentID });
}
Here are my class details
public class MySessionClass
{
public string StockCode { get; set; }
public string StockCodeValue { get; set; }
public string CurrentID { get; set; }
}

Post Model to Controller in ajax

This is My ajax Code
$('#RolesSave').click(function () {
var sRow = JSON.parse(JSON.stringify($('#table').bootstrapTable('getSelections')));
var ID = JSON.stringify(sRow, ["ID"]);
var view = {
CompanyCode: $('#Company').val(),
RolesCode: $('#Roles').val(),
ID,
};
$.ajax({
method: "POST",
url: '#Url.Action("Save")',
data: $('#formData').serialize(),
success: function (data) {
alert(data + '!!!')
},
error: function () {
alert('ERROR')
}
})
})
This is My Controller
[HttpPost]
public IActionResult Save(RightsModel view)
{
return View();
}
and This My Model
public class RightsModel
{
public List<string> ID { get; set; }
public string Company { get; set; }
public string Roles { get; set; }
}
and this is my view
<form id="formData">
#Html.DropDownListFor(m => m.Company, Model.Company)
#Html.DropDownListFor(m => m.Roles, Model.Roles)
<button id="RolesSave" class="btn btn-primary btn-light" type="submit">存檔</button>
<table id="table"></table>
My problem is when I use the code $('#formData').serialize(). It can convert the data in View into Model normally.
But when I use JSON.serialize(view), It can't achieve the same goal.
Even if I add [FormBody] to the Action, I cannot get any relevant information.
Any suggestions?
JSON.serialize is not exists in js,we usually use JSON.stringify.And you need to make sure the model structure of view is the same with model RightsModel.And you need to add contentType:"application/json", to ajax since you want to pass json type data to action.Here is a demo:
js:
$('#RolesSave').click(function () {
var sRow = JSON.parse(JSON.stringify($('#table').bootstrapTable('getSelections')));
var ID = [];
sRow.forEach(function (item, index) {
ID.push(""+item.ID);
});
var view = {
Company: $('#Company').val(),
Roles: $('#Roles').val(),
ID: ID
};
$.ajax({
method: "POST",
url: '#Url.Action("Save")',
data: JSON.stringify(view),
contentType:"application/json",
success: function (data) {
alert(data + '!!!')
},
error: function () {
alert('ERROR')
}
})
})
action:
[HttpPost]
public IActionResult Save([FromBody]RightsModel view)
{
return View();
}
result:
I try yo use var ID = ["1", "2", "3"]; to test,and it can work.ID need to be type List<string>.

Adding via ajax one to one related data .net Core

I have 2 tables, one is a one to one or one to zero relationship:
public class ComponentText
{
[Key]
public int ComponentTextId { get; set; }
public string ComponentContent { get; set; }
public ComponentTextSection ComponentTextSection { get; set; }
}
public class ComponentTextSection
{
[Key]
public int ComponentTextId { get; set; }
public string SectionTitle { get; set; }
public ComponentText ComponentText { get; set; }
}
I can add row fine using usual .net core posting using a form, here is code which does this:
public async Task<IActionResult> OnPostAsync()
{
if (!ModelState.IsValid)
{
return Page();
}
var newComponentText = new ComponentText();
if (await TryUpdateModelAsync<ComponentText>(
newComponentText,
"ComponentText",
i => i.ComponentTextSection, i => i.ComponentContent))
{
_context.ComponentText.Add(newComponentText);
await _context.SaveChangesAsync();
}
return RedirectToPage("./Index");
}
I need to update though via ajax, but I am having issues updating the SectionTitle using this current way. It adds the data to the ComponentText table fine but not the ComponentTextSection table. Here is my ajax code:
function saveWindow() {
var ComponentText = { "ComponentText.ComponentTextSection.SectionTitle": $("#ComponentText_ComponentTextSection_SectionTitle").val(),
"ComponentTextId": $("#ComponentText_ComponentTextId").val(),
"ComponentContent": $("#ComponentText_ComponentContent").val()};
$.ajax({
type: 'PUT',
contentType: 'application/json; charset=utf-8',
headers: {
'RequestVerificationToken': '#AntiForgery.GetAndStoreTokens(HttpContext).RequestToken'
},
data: JSON.stringify(ComponentText),
url: '#Url.Page("Edit", "demo4")',
success: function (result) {
closeWindow();
}
});
}
It must be to do with ComponentText.ComponentTextSection.SectionTitle but I have been trying lots of things to get this to work but failing. Does anyone know how to pass a one to one related data via ajax?
Thanks
For the one-to-one model, if you want to use ajax to transfer the complex nested model to the page, you need to create the same as the ComponentText model structure in saveWindow function of ComponentText variable.
<script>
function saveWindow() {
var ComponentText = {
"ComponentTextSection":
{
"SectionTitle": $("#ComponentText_ComponentTextSection_SectionTitle").val(),
},
"ComponentTextId": 1,
"ComponentContent": $("#ComponentText_ComponentContent").val()
};
$.ajax({
type: 'PUT',
contentType: 'application/json; charset=utf-8',
headers: {
'RequestVerificationToken':
'#AntiForgery.GetAndStoreTokens(HttpContext).RequestToken'
},
data: JSON.stringify(ComponentText),
url: '#Url.Page("Edit", "demo4")',
success: function (result) {
closeWindow();
}
});
}
</script>
Here is the test result:

send complex and simple parameter to web api using ajax

i write web api.
web api controller:
public class TaskApiController : ApiController
{
[HttpPost]
public IHttpActionResult PostNewTask(string xx,string yy,CommonTask Task)
{
...
}
}
and ajax:
var task = new Object();
task.Description = 'kjk';
task.ID = null;
var req = $.ajax({
url: 'http://localhost:3641/api/TaskApi',
contentType: "application/json",
data: {"xx":'admin',"yy":'123',"task": JSON.stringify(task) },
type: 'Post',
success: function (data) {
alert('success');
}
});
req.fail(function (jqXHR, textStatus) {
alert("Request failed: " + jqXHR.responseText);
});
and WebApiConfig:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
when run ajax, return error:
No action was found on the controller 'TaskApi' that matches the request
Always feed the POST methods with class type parameters. Please do the following modification on the API and JavaScript.
1. Create a model class
<pre>
public class Model
{
public string xx { get; set; }
public string yy { get; set; }
public CommonTask Task { get; set; }
}
</pre>
Then modify your Web API to accept a type of your class model
<pre>
public class TaskApiController : ApiController
{
[HttpPost]
public IHttpActionResult PostNewTask([FromBody] Model model)
{
}
}
</pre>
Change your ajax method to pass a json object similar to the Model class
<pre>
var task = new Object();
task.Description = 'kjk';
task.ID = null;
var data = {
"xx": 'admin',
"yy": '123',
"task" : JSON.stringify(task)
};
var req = $.ajax({
url: 'http://localhost:3641/api/TaskApi',
contentType: "application/json",
data: {"model": JSON.stringify(data) },
type: 'Post',
success: function (message) {
alert('success');
}
});
req.fail(function (jqXHR, textStatus) {
alert("Request failed: " + jqXHR.responseText);
});
</pre>

Ajax post model to controller on submit

I have a model class
public class ViewModel
{
public HttpPostedFileBase File {get;set;}
public string FileName {get;set;}
}
Controller
[HttpPost]
public ActionResult Upload(ViewModel model)
{
}
VIEW
$("#myform").on("submit", function (event) {
event.preventDefault();
var formData = {
FileName: $('#fileName').val(),
File: $('#file').get(0).files[0],
};
$.ajax({
url: url,
type: "POST",
data: formData,
contentType:"multipart/form-data",
success: function (resp) {
}
});
I am not able to post my model to the controller? What am i doing wrong?

Resources