value is not pass from view to controller using ajax - 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; }
}

Related

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:

Problems with Post Ajax in Asp.net core MVC

I can not send a Model that I am manually creating to my controller. When I send the request, it's coming up with empty properties. There is something wrong that is hindering the conversion. Does anyone know how to help me?
var operadoraChamadas = {
Id: 0,
Descricao: 'rssrrssr',
PadraoSistema: true
};
var requestData = { operadoraChamadasViewModel: operadoraChamadas}
$.ajax({
url: "/pessoa-gerenciar/changeFormaContato",
type: "POST",
data: JSON.stringify(requestData),
contentType: "application/json",
dataType: "json",
success: function (result) {
alert('ok');
},
error: function () {
alert("Oops! Algo deu errado.");
console.log(requestData);
}
});
[HttpPost]
[Route("pessoa-gerenciar/changeFormaContato")]
public IActionResult changeFormaContato(OperadoraChamadaViewModel operadoraChamadaViewModel)
{
//ViewBag.indice_new = indice;
//return PartialView("~/Views/Pessoa/PessoaContato/_PessoaContatoAdd.cshtml", _pessoaContatoAppService.CreateNew(pessoaNatureza, formaContatoId));
return null;
}
ViewModel:
public class OperadoraChamadaViewModel
{
[Key]
[DisplayName("ID")]
public int Id { get; set; }
[Required(ErrorMessage = "A Descrição é obrigatória")]
[MaxLength(50)]
[DisplayName("Descricao")]
public string Descricao { get; set; }
[DisplayName("Padrão do Sistema")]
public bool PadraoSistema { get; set; }
}
ASP.NET Core requires to add [FromBody] attribute to parameter to parse application/json content
[HttpPost]
[Route("pessoa-gerenciar/changeFormaContato")]
public IActionResult changeFormaContato([FromBody] OperadoraChamadaViewModel operadoraChamadaViewModel)

Passing JSON object to Controller but loose model binding

I am trying to pass a simple JSON object to a controller using MVC3 and JSON. The object gets passed but I loose all the properties. I see all the properties in firebug on the request but am not sure why I am loosing them on the server. Do all the properties of the object need to be set in order for the mapping to work? I am using MVC3 so the binding should be build in. What am I missing?
Class:
[Serializable]
public class StoryNote
{
public int Id { get; set; }
public string Note { get; set; }
public Nullable<int> StoryCardId { get; set; }
public string CreatedBy { get; set; }
public Nullable<System.DateTime> CreateDate { get; set; }
public virtual StoryCard StoryCard { get; set; }
}
JSON:
$(document).ready(function () {
$('#newNote').click(function (e) {
e.preventDefault();
var storynote = {
StoryNote: {
Note: $('#Note').val(),
StoryCardId: $('#StoryCard_Id').val(),
CreatedBy: 'Xyz', }
};
$.ajax({
url: '#Url.Action("PostNote")',
type: 'POST',
data: JSON.stringify(storynote),
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
$('#previousNotes').append(data.Note + '<br/>' + data.CreatedBy + '<br/><hr/>');
},
});
});
});
Controller:
[HttpPost]
public JsonResult PostNote(StoryNote newStoryNote)
{
StoryNote newNote = new StoryNote { Note = newStoryNote.Note, CreatedBy = newStoryNote.CreatedBy, StoryCardId = newStoryNote.StoryCardId, CreateDate = DateTime.Now };
db.StoryNotes.Add(newStoryNote);
return Json(newStoryNote, JsonRequestBehavior.AllowGet);
}
You have a name mismatch in your code - parameter is named "StoryNote" in Javascript code and "newStoryNote" in Controller. Those names should be equal. I believe if you change
var storynote = {
StoryNote: {
Note: $('#Note').val(),
StoryCardId: $('#StoryCard_Id').val(),
CreatedBy: 'Xyz', }
};
to
var storynote = {
newStoryNote: {
Note: $('#Note').val(),
StoryCardId: $('#StoryCard_Id').val(),
CreatedBy: 'Xyz', }
};
then your code should work.

why postify works and stringify doesn't?

In server side I have following class
public class EditorContext
{
public Module Module { get; set; }
public Holder Holder { get; set; }
}
public class Module
{
public string CodeName { get; set; }
public string Content { get; set; }
}
public class Holder
{
public int Id { get; set; }
public int Type { get; set; }
}
public class EditorController : Controller
{
[HttpPost]
public ActionResult AddModule(EditorContext context)
{
return Json(new { });
}
}
From the client I send request like this
var data =
{
Module:
{
CodeName: 1,
Content: 2
},
Holder:
{
Type: 3,
Id: 4
}
};
$.ajax({
type: "POST",
url: 'Editor/AddModule',
data: JSON.stringify(data),
async: false,
success: function () {
},
error: function (xhr, status, error) {
throw new Error();
}
});
1 - Fiddler shows that he sent {"Module":{"CodeName":1,"Content":2},"Holder":{"Type":3,"Id":4}}, but in server Request.Form = %7b%22Module%22%3a%7b%22CodeName%22%3a1%2c%22Content%22%3a2%7d%2c%22Holder%22%3a%7b%22Type%22%3a3%2c%22Id%22%3a4%7d%7d, WHY?
2 - If instead of "JSON.stringify(data)" I use "postify" like in here, so EditorController.AddModule gets already filled EditorContext. This postify change the data to "Model.CodeName=1&Model.Content=2&Holder.Type=3&Holder.Id=4". So, why in this way EditorContext is filled automatically by default binder and in (1) it doesn't?
Thank you
You need to tell the binder that your data is JSON, otherwise it has no idea it should be parsing it as such. Add the correct content type header to your request:
$.ajax({
type: "POST",
url: 'Editor/AddModule',
data: JSON.stringify(data),
contentType: "application/json",
async: false,
success: function () {
},
error: function (xhr, status, error) {
throw new Error();
}
});

MVC3 Ajax Get String and post it back

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)
{
...
}
}

Resources