Ajax call return always a null object - ajax

I know there are a lot of similar posts about this topic but I'm still not able to solve my problem.
I'm trying to call an ActioResult method with a button from my controller through ajax.
The problem is I always get back a null object
I'm quiet sure the problem is that I'm not able to bind the ajax call with the controller in the "data: " field
The AJAX call:
$(document).ready(function () {
$(".milkmilk").click(function () {
$.ajax({
type: "POST",
url: '#Url.Action("GoatMilk", "User")',
datatype: "html",
data: { name: 'name' },
success: function (data) {
$(this).closest('[data-rel]').html(data);
},
error: function (data) {
alert("error!");
}
});
});
});
The controller:
public ActionResult GoatMilk(string name)
{
var rep = new GoatRepository();
var goat = rep.GetAnimal(name);
if(goat != null)
{
var model = FarmFactory.CreateAnimalModel<GoatViewModel>(goat) as GoatViewModel;
model.Milk = rep.MilkProduction(goat);
_MyEchoFarmDB.Update(goat);
var rek = new FarmRepository();
var deposit = rek.GetDeposit(name);
deposit.Milk = goat.Milk;
db.Update(deposit);
return Json(model.Milk, JsonRequestBehavior.AllowGet);
}
return View();
}
The Html code
#foreach (var item in Model)
{
<tbody>
<tr>
<td>
<button class="milkmilk" data-rel="item.Name">MILK</button>
</td>
</tr>
</tbody>
}
The code never enters inside the if(goat != null), so I always get back an error (notice that without the Ajax call the method works just fine)
Thank you!

It may not be the cleanest way to solve this, but seems to run smoothly
HTML:
<td>
<button type="button" class="milk" data-rel="#item.Name">MILK</button>
<p class="milkGoat">#item.Milk</p>
</td>
Controller:
public JsonResult GoatMilk(string name)
{
return Json(model.Milk, JsonRequestBehavior.AllowGet);
}
Ajax:
<script type="text/javascript">
$(document).ready(function () {
$(".milk").click(function () {
var name = $(this).data('rel');
var me = $(this)
$.ajax({
type: "POST",
url: '#Url.Action("GoatMilk", "User")',
datatype: "html",
data: { name: name },
success: function (milk) {
me.next(".milkGoat").html(milk);
},
error: function (milk) {
alert("error!");
}
});
});
});
</script>

instead of ActionResult try JsonResult method to return
public JsonResult GoatMilk()
{
return Json();
}

Related

Razor not printing Values to screen after ASP 3.1 RazorPages AJAX Post Updates Model

Hello I am updating a model with an AJAX call on the event of a dropdown selection.
The model is updated and when I step through the below razor loop the values exist.
However nothing inside the #if statement prints to the screen, not even the H2.
The div is just empty... Thoughts?
#if (Model.FieldsRequiredOnStart != null)
{
foreach (var item in Model.FieldsRequiredOnStart)
{
for (int i = 0; i < #item.Inputs.Count(); i++)
{
<h2>Fields Required on Start</h2>
var x = #item.Inputs[i];
<span>#x.Name</span>
<input placeholder="#x.Name" maxlength="#x.MaxSize" type="#x.InputType"> <input />
}
}
}
function onSelect(e) {
let id = $("#wfDropdown").data("kendoDropDownList").value()
if (e.item) {
$('#wfDefId').val(id)
} else {
$('#wfDefId').val(id)
}
$.ajax({
type: 'Post',
url: '/CreateNewWorkflow?handler=RequiredInputs',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { Id: id },
success: function () {
}
});
}
EDIT ON SUCCESS:
I ended up using the Partial View solution. My issue was I was not sending a refreshed model when I had previously tried the partial way. The Second answer is also valid. Gotcha: If you make a partial be sure to remove the #Page reference at the top or you will get Model is null errors.
Also worth noting the C# Syntax I had to use was slightly different than what is provided in the answer to return the Partial view..
public ActionResult OnPostRequiredInputs(int id)
{
//DO STUFF
//Refresh Model to pass to partial
IEnumerable<Razor.PageModels.CreateWorkflowNames> namelist = da.GetWfDefVersionNameAndIds();
var freshModel = new CreateNewWorkflowModel(_cache, _mapper, _wlog, _workflowFactory, _configuration)
{
FieldsRequiredOnStart = entityDefinitionFieldsList,
CreateWorkflowModel = namelist
};
return Partial("/Pages/_CreateNewWorkflowRequiredFieldsPartial.cshtml", freshModel);
}
Assuming your CreateNewWorkflow controller action returns a model rehydrated with the new data, you should be able to set that new data in the onSuccess callback of your ajax request.
I'd do this to accomplish the result.
Create partial view for the razor we're gonna need to refresh.
//Filename: YourView.cshtml
<div id="partialWrapper"></div>
//File name: _YourPartialView.cshtml
#if (Model.FieldsRequiredOnStart != null)
{
foreach (var item in Model.FieldsRequiredOnStart)
{
for (int i = 0; i < #item.Inputs.Count(); i++)
{
<h2>Fields Required on Start</h2>
var x = #item.Inputs[i];
<span>#x.Name</span>
<input placeholder="#x.Name" maxlength="#x.MaxSize" type="#x.InputType"> <input />
}
}
}
Make sure your controller action returns a partial view.
public IActionResult<YourModelClass> CreateNewWorkflow(YourRequestClass request) {
//your logic
//...
var rehydratedModel = new YourModelClass(); //actually fill this with data
return PartialView(rehydratedModel);
}
Set the partial view result to your wrapper div in the onSuccess call back.
function onSelect(e) {
let id = $("#wfDropdown").data("kendoDropDownList").value()
if (e.item) {
$('#wfDefId').val(id)
} else {
$('#wfDefId').val(id)
}
$.ajax({
type: 'Post',
url: '/CreateNewWorkflow?handler=RequiredInputs',
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
data: { Id: id },
success: function (data) { //data represents your partial view
$('#partialWrapper').html(data) //set partial view
}
});
That is a pretty typical flow of how you refresh razor pages with ajax.
Razor not printing Values to screen after ASP 3.1 RazorPages AJAX Post Updates Model, The div is just empty
The issue is related to the Ajax success function, according to your code, we can see that you didn't do anything to update the page with the latest data.
Generally, after getting the latest data in the success function, we could use JQuery to find the page elements and bind the latest data or populate the new page element to replace the old data. You could refer to the following sample code:
<select id="ddl1" asp-for="CategoryId" asp-items="Model.Categories">
<option value="">Select Category</option>
</select>
<h4>SubCategories</h4>
#if (Model.SubCategories != null)
{
<table >
<tr><th>SubCategoryId</th><th>CategoryId</th><th>SubCategoryName</th></tr>
<tbody id="tbody">
#foreach (var item in Model.SubCategories)
{
<tr>
<td>#item.SubCategoryId</td>
<td>#item.CategoryId</td>
<td>#item.SubCategoryName</td>
</tr>
}
</tbody>
</table>
}
Code in the cshtml.cs file:
private ICategoryService _categoryService;
public DDLpageModel(ICategoryService categoryService)
{
_categoryService = categoryService;
}
[BindProperty(SupportsGet = true)]
public int CategoryId { get; set; }
public int SubCategoryId { get; set; }
public SelectList Categories { get; set; }
public List<SubCategory> SubCategories { get; set; }
public void OnGet()
{
Categories = new SelectList(_categoryService.GetCategories(), nameof(Category.CategoryId), nameof(Category.CategoryName));
SubCategories = _categoryService.GetSubCategories(1).ToList();
}
public JsonResult OnGetSubCategories()
{
return new JsonResult(_categoryService.GetSubCategories(CategoryId));
}
Then, in the Ajax success function, find the element and set the value or dynamic add page elements with the latest data and replace the old one.
#section scripts{
<script>
$(function () {
$("#ddl1").on("change", function () {
var categoryId = $(this).val();
//method 1: using JQuery Ajax get the latest data and update the main page content
$.ajax({
url: `?handler=SubCategories&categoryId=${categoryId}`,
contentType: 'application/json; charset=utf-8',
type: 'get',
dataType: 'json',
success: function (data) {
$("#tbody").html("");
//loop through the data and append new data to the tbody
$.each(data, function (i, item) {
$("#tbody").append("<tr><td>" + item.subCategoryId + "</td><td>" + item.categoryId + "</td><td>" + item.subCategoryName + "</td></tr>");
});
}
});
});
});
</script>
}
Besides, you could also create a Partial page (for example: _SubCategories.cshtml):
#model List<SubCategory>
<table class="table table-striped">
<tr><th>SubCategoryId</th><th>CategoryId</th><th>SubCategoryName</th></tr>
<tbody id="tbody">
#foreach (var item in Model)
{
<tr>
<td>#item.SubCategoryId</td>
<td>#item.CategoryId</td>
<td>#item.SubCategoryName</td>
</tr>
}
</tbody>
</table>
In the main page .cshtml.cs file, add the following handler:
public PartialViewResult OnGetSubcategoryPartial()
{
var subcategories = _categoryService.GetSubCategories(CategoryId).ToList();
return Partial("_SubCategories", subcategories);
}
Then, using JQuery Ajax to call the above handler and load the partial page:
<h2>Using Partial Page</h2>
<select id="ddl2" asp-for="CategoryId" asp-items="Model.Categories">
<option value="">Select Category</option>
</select>
<div id="output">
</div>
#section scripts{
<script>
$(function () {
$("#ddl2").on("change", function () {
var categoryId = $(this).val();
$.ajax({
url: `?handler=SubcategoryPartial&categoryId=${categoryId}`,
contentType: 'application/html; charset=utf-8',
type: 'get',
dataType: 'html',
success: function (result) {
$("#output").html("");
$("#output").append(result);
}
});
});
});
</script>
}
The screenshot like this:

Ajax PostBack: Read data from Controller

How do I read the data from my controller in my ajax postback?
I have a Razor form
#using (Html.BeginForm("CreateDocument", "Pages", FormMethod.Post, new { id = "createDocumentForm" }))
{
....
}
And I catch the Submit action in JavaScript:
<script type="text/javascript">
$(document).ready(function () {
$("#createDocumentForm").submit(
function () {
showWaitMode();
$.ajax({
data: ("#createDocumentForm").serialize,
success: (e) => {
console.log(e);
},
error: (errorResponse) => {
alert(errorResponse)
}
})
return false;
}
);
});
</script>
In my controller I hit this method:
public ActionResult CreateDocument(NotatFletModel model)
{
var reuslt = new
{
Staus = true,
GoDocumentId = model.ContactId.ToString(),
ErrorMessage = model.DocumentKindId,
};
return Json(reuslt);
}
But in my Ajax success function I would like to get the data from my contorller. I expected it to be in my parameter e but it's not
So in short: How do I do an Ajax post and read the data posted back from the controller
Checkout my code for Form Post using ajax
Html :
#using (Html.BeginForm("CreateDocument", "Pages", FormMethod.Post, new { id = "createDocumentForm" }))
{
....
}
Jquery :
$("#createDocumentForm").submit(
function (e) {
showWaitMode();
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
url: url,
type: 'POST',
data: form.serialize(), // serializes the form's elements.
success: function (data) {
console.log(data); // show response
},
error: (errorResponse) => {
alert(errorResponse)
}
})
return false;
}
);
Controller :
//You can Use FormCollection also to get data
//public ActionResult CreateDocument(FormCollection fc) {
[HttpPost]
public ActionResult CreateDocument(NotatFletModel model) {
//your logic
return Json(model, JsonRequestBehavior.AllowGet);
}

Ajax call not working in foreach loop in MVC

I'm dynamically adding data to the database using AJAX and displaying them using foreach loop in MVC, I have also added a button to remove the those data using ajax call.
HTML/MVC code:
<div id="divaddrules" class="form-group row">
#try
{
foreach (var item in ViewBag.AdditionalRules)
{
<div class="col-sm-10">
<p style="font-size:large">#item.AdditionalDesc</p>
</div>
<div class="col-sm-2">
<input type="button" onclick="Removeinput(#item.id)" class="text-dark" style="border:none; background-color:transparent" value="X" />
</div>
}
}
catch (Exception ex){ }
</div>
Now when I click on Remove button it call the following JS code:
function Removeinput(id) {
var datas = {};
datas.addId = id
$.ajax({
url: "/Rooms/RemoveAdditionalRules",
type: "GET",
data: datas,
success: function (result) {
alert(result.id);
$("#divaddrules").load(window.location.href + " #divaddrules");
},
error: function (result) {
alert("Error: " + result.status);
}
});
}
and its passing to this controller:
[HttpGet]
[Authorize]
public ActionResult RemoveAdditionalRules(int addId)
{
HouseRules rules = db.HouseRules.Find(addId);
db.HouseRules.Remove(rules);
db.SaveChanges();
return Json(JsonRequestBehavior.AllowGet);
}
I'm getting 500 error on ajax call error.
Can anyone tell me where I'm doing it wrong? Please.. I'm stuck here.
Update:
Attached screenshot: Debug Screenshot
Write your Removeinput function as follows:
function Removeinput(id) {
$.ajax({
url: "/Rooms/RemoveAdditionalRules",
type: "GET",
data: { addId : id},
success: function (response) {
alert(response);
$("#divaddrules").load(window.location.href + " #divaddrules");
},
error: function (result) {
alert("Error: " + result.status);
}
});
}
Then in the controller method:
[HttpGet]
[Authorize]
public ActionResult RemoveAdditionalRules(int addId)
{
AdditionalRules rules = db.AdditionalRules.Find(addId); // Here was the problem. He was pointing to the wrong table that has fixed over team viewer.
db.AdditionalRules.Remove(rules);
db.SaveChanges();
return Json(addId,JsonRequestBehavior.AllowGet);
}
the problem it is missing values on db, in the image you ask to id 25 but return null and you try to remove a item passing null value.
so in your case you need to validate before remove or fix the missing data:
[HttpGet]
[Authorize]
public ActionResult RemoveAdditionalRules(int addId)
{
HouseRules rules = db.HouseRules.Find(addId);
If(rules == null)
{
//return error msg.
return Json(JsonRequestBehavior.AllowGet);
}
db.HouseRules.Remove(rules);
db.SaveChanges();
return Json(JsonRequestBehavior.AllowGet);
}
make your input type submit, may this was helpful
function deleterelation(id) {
debugger;
if (id > 0)
$.ajax({
url: "/Relations/Delete/" + id,
type: "get",
datatype: "json",
data: { id: id },
success: function (response) {
debugger;
if (response != null) {
$("#txtDName").text(response.name);
$("#DRelationId").val(response.id);
$("#DeleteRelation").modal("show");
}
},
error: function (response) {
$("#DeleteRelationLoading").hide();
$("#DeleteRelation_btn_cancel").show();
$("#DeleteRelation_btn_save").show();
}
});
else
toastr.error("Something went wrong");
}
<input type="submit" onclick="Removeinput(#item.id)" class="text-dark" style="border:none; background-color:transparent" value="X" />
if this not work plz let me know

Cannot bind JSon with MVC 3 controller data using KnockoutJS

I am new to javascript and MVC 3. I am developing a sample application to get familiar with KnockoutJs.
I am passing a c# object with some properties to a controller. Than this object is passed to the View serialized as JSon. Then I am using the data with Knockout in my view and want to return this data back to the server. But the binding with the the server data fails for on of my properties.
Here is my code:
Model:
public class FranchiseInfo
{
public string FullName { get; set; }
public string ShortName { get; set; }
public List<string> ServerIps = new List<string>();
}
Controller with sample data returning JSon to the View:
public JsonResult Data()
{
FranchiseInfo franchiseInfo = new FranchiseInfo();
franchiseInfo.FullName = "PokerWorld";
franchiseInfo.ShortName = "PW";
franchiseInfo.ServerIps.Add("192.111.1.3");
franchiseInfo.ServerIps.Add("192.112.1.4");
return Json(franchiseInfo, JsonRequestBehavior.AllowGet);
}
Javascript file using knockout:
$(function () {
function viewModel() {
var self = this;
self.FullName = ko.observable();
self.ShortName = ko.observable();
self.optionValues = ko.observableArray([]);
self.ServerIps = ko.observableArray([]);
$.getJSON("Home/Data", function (data) {
self.FullName(data.FullName);
self.ShortName(data.ShortName);
self.optionValues([data.FullName, data.ShortName]);
for (var i = 0; i < data.ServerIps.length; i++) {
self.ServerIps.push({ name: ko.observable(data.ServerIps[i]) });
}
});
self.addIp = function () {
self.ServerIps.push({ name: ko.observable("0.0.0") });
}
self.showIps = function () {
alert(self.ServerIps[name]);
}
self.save = function () {
$.ajax({
url: "Home/Save",
type: "post",
data: ko.toJSON({ FullName: self.FullName, ShortName: self.ShortName, ServerIps: self.ServerIp }),
contentType: "application/json",
success: function (result) { alert("result") }
});
}
};
ko.applyBindings(new viewModel);
View:
Full Name:
<span data-bind="text: FullName"></span>
<input data-bind="value: FullName" />
</div>
<div>
Short Name:
<span data-bind="text: ShortName"></span>
</div>
<select data-bind="options: optionValues"></select>
<div data-bind="foreach: ServerIps">
Name:
<input data-bind="value: name" />
<span data-bind="text: name" />
</div>
<div data-bind="text: ko.toJSON(ServerIps)"></div>
<button data-bind="click: addIp">Add IP</button>
<button data-bind="click: save">Save</button>
When Save button is clicked the data is sent to the server in Json format:
Here is the controller:
public JsonResult Save(FranchiseInfo franchiseInfo)
{
//some data here
//return Json result
}
Full name and Short name properties bind correctly with the c# model when I am sending them in Json format back to the server but the ServerIps property which is an array cannot bind. I think because it is in the format { name: ip} and the model property ServerIps is of type List. How can I fix this ? Any help with working example will be appreciated. Thanks.
I had the same problem in Java Spring.
We solved it by serializing the ViewModel as a request string.
We wrote the function ourselves (although you might want to check if the 'value' is an array and go a bit recursive):
function serializeViewModelToPost(dataString) {
var data = ko.toJS(dataString);
var returnValue = '';
$.each(data, function (key, value) {
returnValue += key + '=' + value + '&';
});
return returnValue;
}
Another option is to parse it serverside:
link
UPDATE:
self.save = function () {
$.ajax({
url: "Home/Save",
type: "post",
data: serializeViewModelToPost(this)),
success: function (result) { alert("result") }
});
You still need to edit the serialize function to check for arrays.

How to use ajax call to pass json data to controller and render a partial view as result?

I need to pass model object to controller, and from there to call service to generate data for the partial view. I am able to pass the json object to the main view, and I am able to generate the partial view. However, I am having difficulties to render the partial view in the main view after the call. If I don't pass object to controller, I am able to render the partial view.
My Main goal is: to pass json object and render partial view with the same ajax call.
Would appreciate help on this.
I apologize for the lengthy code here, but not sure how I could do it some other way.
The following code works, where I do not pass Json object via ajax call, and create department object in the controller:
main view code:
#model PartialViewDemo.Models.School
....
<body>
....
<div>
#Html.Partial("_MyPartialView", Model.Department )
</div>
....
<div id="divTest"></div>
<input type="button" value="Click" id="btnClick"/>
</body>
<script src="~/Content/jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$(function() {
$('#btnClick').click(function(data) {
var dept = {
DepartmentName: "test Dept",
DepartmentRule: "test rule",
Comment:" test comment"
};
$.ajax({
url: '/home/ShowPartailView/',
success: function (result) {
$('#divTest').html(result);
},
failure: function (errMsg) {
alert(errMsg);
}
});
});
});
</script>
controller code:
public ActionResult Index()
{
var model = new School();
model.Department = GetDepartmentList(3);
return View(model);
}
public List<Department> GetDepartmentList(int counter)
{
var model = new List<Department>();
for (var i = 1; i <= counter; i++)
{
var data = new Department();
data.DepartmentName = "Dept " + i;
data.DepartmentRule = "Rule " + i;
data.Comment = "Comment " + i;
model.Add(data);
}
return model;
}
public PartialViewResult ShowPartailView()
{
Department dept = new Department()
{
DepartmentName = "test Dept",
DepartmentRule = "test rule",
Comment = "We Rock!"
};
PartialViewResult result = PartialView("_MySecondPartialView", dept);
return result;
}
Partial view code:
#model PartialViewDemo.Models.Department
<h2>_MyView from partial view using PartialView</h2>
#if (Model != null)
{
<div>
<table>
<thead>
....
</thead>
<tbody>
<tr>
<td>#Model.DepartmentName</td>
<td>#Model.DepartmentRule</td>
<td>#Model.Comment</td>
</tr>
</tbody>
</table>
</div>
}
Model:
public class Department
{
public string DepartmentName { get; set; }
public string DepartmentRule { get; set; }
public string Comment { get; set; }
}
public class School
{
public List<Department> Department { get; set; }
}
However, when I pass in Json object to ajax call with all other code stay the same, except the following changes, the partial view won't show with click event.
$.ajax({
url: '/home/ShowPartailView/',
data: JSON.stringify(dept),
dataType: 'json',
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (result) {
$('#divTest').html(result);
},
failure: function (errMsg) {
alert(errMsg);
}
});
with controller code:
public PartialViewResult ShowPartailView(Department dept)
{
PartialViewResult result = PartialView("_MySecondPartialView", dept);
return result;
}
In the second example where you pass the object, you have specified the
dataType: 'json',
ajax option but your controller method is returning a partial view so it needs to be
dataType: 'html',
Side note: You can omit the contentType option and just use data: dept,
If you have return partial view then try this to render partial view in Div or any other element.
$(document).ready(function () {
$.ajax({
url: '/YourContollerName/YourActionName',
type: "POST"
})
.success(function (result) {
$('.loadOnDivClass').empty();
$('.loadOnDivClass').html(result);
})
.error(function (status) {
alert(status);
})
});
If Contrller Action return like this
return PartialView("_PartialList",modelObj);

Resources