I have a page, which will send back the serialzed Model to the controller. In this case I'm using ajax.
In the View I have the following code:
#Html.Hidden("processViewModel", new Microsoft.Web.Mvc.MvcSerializer().Serialize(Model, SerializationMode.Signed))
And the controller looks like this:
[HttpPost]
public ActionResult PreviewSample([Deserialize]ProcessViewModel processViewModel /*FormCollection form*/)
and here is my ajax code:
function GetPreview() {
var json = $('form').serializeObject();
complete = false;
json['ProcessDTO.FileUploadDTO.TempUploadFileDTO.FileInformation.HasHeader'] = false; // $('input[name="ProcessDTO.FileUploadDTO.TempUploadFileDTO.FileInformation.HasHeader"]').is(':checked');
alert($('input[name="ProcessDTO.FileUploadDTO.TempUploadFileDTO.FileInformation.HasHeader"]').is(':checked'));
var jsonData = JSON.stringify(json);
var url = ROOT + '/request/previewsample/';
if (lastPreviewCall != undefined) {
if (lastPreviewCall.status != 200) {
lastPreviewCall.abort();
}
}
lastPreviewCall = $.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
// dataType: 'json',
data: jsonData,
otherParam: true,
async: true,
success: function (res) {
$('#preview').find('tbody').find('tr').remove();
var selected = $('.addressType:checked').attr('data-hideClass');
for (var i = 0; i < res.PreviewData.length; i++) {
var entry = '<tr>';
var row = res.PreviewData[i];
for (var u = 0; u < row.length; u++) {
if (u == 0 && selected == 'consumer') {
entry += '<td></td>';
}
else {
entry += '<td><span>' + row[u] + '</span></td>';
}
}
entry += '</tr>';
$('#preview').find('tbody').append(entry)
}
}
});
}
So now I have a checkbox, which is default true in this model and when I uncheck it, the ajax will send the serialized model back to the controller, but the checkbox has always the value true.
how can i update the model?
Thanks for any help.
The solution is to add
TryUpdateModel(processViewModel);
in the controller, and then is everything fine...
Related
I'm trying to send data to the controller using this AJAX call of type POST but it's sending null values to the controller. Through this code I want to make new records in the Microsoft Dynamics 365 CRM database.
var formdata = new FormData();
var rowCount = $(".newRow").length;
var projectarray = [];
var datearray = [];
var amountarray = [];
for (var i = 0; i < rowCount; i++) {
projectarray[i] = $("#ProjectType_" + i).val();
datearray[i] = $("#ClaimExpenseDate_" + i).val();
amountarray[i] = $("#Amount_" + i).val();
}
formdata.append("projectarray", projectarray);
formdata.append("datearray", datearray);
formdata.append("amountarray", amountarray);
$.ajax({
url: "#Url.Action("SetClaimDetails", "Claim")",
type: "POST",
data: formdata,
processData: false,
contenttype: false,
success: function (data) {
debugger;
window.location.href = "ess/claim";
alert("Submit Successful!");
},
error: function (err) {
window.location.href = "";
alert("Submit Failed!");
}
});
Here is my controller method which is storing null values instead of the values passed by the AJAX call. And because of this I'm not able to create new records in the database.
public ActionResult SetClaimDetails(string projectarray, string datearray, string amountarray)
{
try
{
Entity item = new Entity("bam_expenseclaims");
item["bam_expdate"] = Convert.ToDateTime(datearray);
item["bam_amount"] = amountarray;
item["bam_project"] = new EntityReference("new_project", Guid.Parse(projectarray));
globalService.Connection.Create(item);
}
catch (Exception ex)
{
XmlConfigurator.Configure();
ILog log = LogManager.GetLogger("TechnicalErrorAppender");
log.Error(string.Empty);
throw ex;
}
return View(Constant.CLAIMPATH);
}
Someone helped me with this yesterday but it's now messed up how I send a string query to my endpoint in the AJAX call.
Functionally, this script works but by converting searchResult to an array, it screwed up my ajax call and what I send as a string query to an endpoint.
How can I modify this to make sure it sends searchResult as a string again to my ajax?
$('#productInput').on('input', function () {
let _this = $(this);
let foundOption;
let searchResult = [];
let optSelector = `option[value='${_this.val()}']`;
if (_this.val() === '') {
return;
} else if ((foundOption = $('#returnedProducts').find(optSelector)).length) {
$("#groupName").val(searchResult[$(foundOption).attr('srindex')]._source);
$("#groupNum").val(searchResult[$(foundOption).attr('srindex')]._source);
} else {
$.ajax({ url: '/account/autocomplete',
data: {
search_result: searchResult
},
"_token": "{{ csrf_token() }}",
type: "POST",
success: function (response) {
console.log(response);
let searchResult = response.hits.hits;
console.log(searchResult);
$("#returnedProducts").empty();
for(let i = 0; i < response.hits.hits.length; i++) {
$("#returnedProducts").append("<option value=" + searchResult[i]._source.category + ">" + searchResult[i]._source.category + "</option>");
}
}
});
}
});
I hope developers can support me, I have minimal experience in the use of java script.
After investigating and several attempts, I was able to load a dropdownlist with data from a LINQ query and pass as a parameter the value of a textbox.
What I could not do is from the query Linq get two fields (Id and value) send them to the dropdownlist and show the value but after being able to use the Id of that field to be able to use it in a create, currently I can only show the value but I need the Id too.
View
#Html.TextBox("CP", "", new { #id = "txtCP", #onchange = "FillOption();", #placeholder = "Codigo Postal" })
#Html.DropDownList("Asentamientos", ViewBag.Drop as List<SelectListItem>)
Script
<script>
function FillOption() {
var CP = $('#txtCP').val();
$.ajax({
type: "Post",
url: "/Home/GetAsentamiento",
data: { CP: CP },
dataType: 'json',
success: function (data) {
$("#Asentamientos").empty();
for (var i = 0; i < data.length; i++) {
$('#Asentamientos').append('<option value=' + data[i].Value + '>' + data[i].Text + '</option > ');
}
}
});
}
</script>
Controllers
public ActionResult Index()
{
List<SelectListItem> drop = new List<SelectListItem>
{
};
ViewBag.Drop = drop;
return View();
}
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select p.Asentamiento).ToList();
SelectList lista = new SelectList(drop2);
ViewBag.lista = lista;
return Json(ViewBag.lista);
}
I think of something like
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { p.IdCodigoPostal,p.Asentamiento}).ToList();
SelectList lista = new SelectList(drop2);
ViewBag.lista = lista;
return Json(ViewBag.lista);
}
but I do not know how the id and the value would be handled
Thanks
If I understand your question correctly, I think you need to name the fields of the object you are creating with the Linq expression, so that it would look something like this:
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { id = p.IdCodigoPostal, value = p.Asentamiento}).ToList();
SelectList lista = new SelectList(drop2);
ViewBag.lista = lista;
return Json(ViewBag.lista);
}
Here are a few examples: https://code.msdn.microsoft.com/LINQ-to-DataSets-09787825#SelectAnonymousTypes1
Then you could access those fields from you javascript with data[i].id and data[i].value.
I hope this helps.
I suspect your issue is around pulling the data from the API result. You're setting the a new property in the ViewBag, then returning the ViewBag property. This really shouldn't be required, and you should instead just return your list, list so (Note: and SelectItemList has a property called "Items" which contains all items you've added):
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { p.IdCodigoPostal,p.Asentamiento}).ToList();
SelectList lista = new SelectList(drop2);
return Json(lista.Items);
}
This should return just a nice list of ListItems. You could also just change your jQuery to loop through the items property, like so:
<script>
function FillOption() {
var CP = $('#txtCP').val();
$.ajax({
type: "Post",
url: "/Home/GetAsentamiento",
data: { CP: CP },
dataType: 'json',
success: function (data) {
$("#Asentamientos").empty();
for (var i = 0; i < data.Items.length; i++) {
$('#Asentamientos').append('<option value=' + data.Items[i].Value + '>' + data.Items[i].Text + '</option > ');
}
}
});
}
</script>
Thanks to all, the code works as follows
Controller
[HttpPost]
public ActionResult GetAsentamiento(string CP)
{
var drop2 = (from p in db.CodigosPostales where p.CodigoPostal == CP select new { Value = p.IdCodigoPostal, Text= p.Asentamiento }).ToList();
SelectList lista = new SelectList(drop2);
return Json(lista.Items);
}
Script
<script>
function FillOption() {
var CP = $('#txtCP').val();
$.ajax({
type: "Post",
url: "/Home/GetAsentamiento",
data: { CP: CP },
dataType: 'json',
success: function (data) {
$("#Asentamientos").empty();
for (var i = 0; i < data.length; i++) {
$('#Asentamientos').append('<option value=' + data[i].Value + '>' + data[i].Text + '</option > ');
}
}
});
}
I am working on an java spring application that requires the controller to return json. By receiving that json in jquery success method, I want to make html out of it.
controller returns a json like below:
return "[{\"Id\": \"1\", \"Name\": \"Apples\"}, {\"Id\": \"2\", \"Name\":\"Mangoes\"}]";
jquery used to hit that controller and then receive the json in success method:
var content;
$(document).ready(function(){
$("#submitButton").click(function(e){
var formData = getFormData();
if(formData!=false){
$.ajax({
type: 'POST',
'url': 'http://localhost:8080/Test_ReportingUI/fieldMappingNext.htm',
data: {jsonData: JSON.stringify(formData)},
dataType: 'json',
success: function(response){
for (var x = 0; x < response.length; x++) {
content = response[x].Id;
content += "<br>";
content += response[x].Name;
content += "<br>";
$(content).appendTo("#Fruits");
}
},
timeout: 10000,
error: function(xhr, status, err){
if(response.status=='timeout')
{
alert('Request time has been out','');
}
console.log(status,err);
}
}); }
});
});
below is the HTML div where I want to use above content to append:
<div id="Fruits">
fruits :
</div>
it is reaching to the controller. and also returning json. but I am not able to use that json.
Replace your for loop with
for (var x = 0; x < response.length; x++)
{
content = "<div class='fruit'><div>" + response[x].Id + "</div>";
content += "<div>" + response[x].Name + "</div></div>";
$(content).appendTo("#Fruits");
}
Your error message correctly explained that you were not appending the correct expression into the fruits
try below code
$(document).ready(function() {
$("#submitButton").click(function(e) {
var formData = getFormData();
if (formData != false) {
$.ajax({
type: 'POST',
'url': 'http://localhost:8080/Test_ReportingUI/fieldMappingNext.htm',
data: {
jsonData: JSON.stringify(formData)
},
dataType: 'json',
success: function(response) {
for (var x = 0; x < response.length; x++) {
var fContent = $("<div></div>");
var id = $("<span></span>").text(response[x].Id);
var name = $("<span></span>").text(response[x].Name);
fContent.append(id)
fContent.append(name);
$("#Fruits").append(fContent);
}
},
timeout: 10000,
error: function(xhr, status, err) {
if (response.status == 'timeout') {
alert('Request time has been out', '');
}
console.log(status, err);
}
});
}
});
});
I am trying to send the following values from view to controller
var ParamAliasArray = new Object();
for (var i = 1; i <= 1; i++) {
ParamAliasArray[i] = $("#txtParamAlias" + i).val();
}
var ParamValueArray = new Object();
for (var i = 1; i <= 4; i++)
{
ParamValueArray[i] = new Array();
for (var j = 1; j <= 1; j++) {
ParamValueArray[i][j] = $("#txtParamValue" + i).val();
}
}
one is 1D array and other is 2D array I am passing as
jQuery.ajaxSettings.traditional = true
$.ajax({
type: 'Post',
dataType: 'json',
url: 'Register/GetRegDataFromuser',
data: JSON.stringify({ GloabalAppID: GlobalAppID,
TransactionID: TransactionID,
OwnerID: OwnerID,
ParamAliasArray: ParamAliasArray,
ParamValueArray: ParamValueArray }),
contentType: 'application/json; charset=utf-8',
async: false,
success: function (data) {
console.debug(data);
},
error: function (data) {
console.debug(data);
}
});
I have written Action method as in
public ActionResult GetRegDataFromuser(int GloabalAppID, int TransactionID, string OwnerID, string[] ParamAliasArray, string[][] ParamValueArray)
{
---some logic--
}
So,I am not able to pass the array to the action method from View..Please help me out.
Thanks in advance.
you need to add ParamValueArray[i][j]=new Array(); this line.