How to bind IDictionary data in a Webgrid - asp.net-mvc

i have a ajax call which calls the ControllerName "Floor" and ActionMethod "GetHotelingList".i have a Dropdown list facility. when i select option from the Dropdownlist list the control goes to ajax call.based on selection value, the Webgrid must be displayed. #grdHoteling is Webgrid id.
$.ajax({
type: 'GET',
url: '/Floor/GetHotelingList',
cache: false,
contentType: 'application/html; charset=utf-8',
dataType: 'html',
data: { floorId: floorId },
success: function (data) {
debugger;
$("#grdHoteling").val(data);
//debugger;
//$("#grdHoteling").html(data);
},
complete: function () {
},
error: function () {
if (facilityName.indexOf('-') != -1) {
$('#floor').empty();
return;
}
else
alert("Error in generating hoteling information");
}
});
Here is the ActionMethod GetHotelingList value is paased floorId for some fileration.
public List<IDictionary> GetHotelingList(int floorId)
{
var model = new List<IDictionary>();
using (var context = new FloorContext())
{
try
{
model = ListHotelingByFloorId(context, floorId);
}
catch (Exception ex)
{
}
}
return model;}
On Success of the ajax call, when i check through debugger am getting data as "System.Collections.Generic.List`1[System.Collections.IDictionary]" and child cannot be evaluated.
kindly help...!
thanks...!

Related

My partial view does not refresh after AJAX call

I am having an issue not able to refresh my Partial view.
my cshtml page page
<script type="text/javascript">
$(document).ready(function () {
$('#btncreate').click(function () {
var projectid = $("#txtprojectid").val();
$.ajax({
url: '/Projects/CreateFinanceItems?pid=' + Id,
datatype: 'json',
type: "POST",
success: function (response) {
alert("record created successfully");
if (response != null) {
window.close();
refreshpartial();
}
}
})
});
function refreshpartial()
{
$.ajax({
url: '/Projects/PartialItem?id=' + "Test",
datatype: 'json',
success: function (response) {
$("#displayproContainer").html(response);
},
error: function (xhr, ajaxOptions, thrownError) {
}
})
}
});
</script>
I can see record created successfully alert message, but when it goes to refreshpartial method my partialview does not refresh with Added data. I put the alert in success function it does not hit.
Partialview DIV ID #displayproContainer
$("#displayproContainer").html(response);
Controller code
[OutputCache(Duration = 0)]
public PartialViewResult PartialItem(string id)
{
// Logic to Insert data
return PartialView(viewModel);
}
Something I am missing here?

ASP.NET MVC form on a Partial View

I have page witha table and a button. When I push the button a partial view loads into a div. On the partial view there is an ajax form which sends back the partial view with validation error in case of wrong form data but I want to remove the partial view and refresh the table in case of successful insertion.
The form header:
#using (Ajax.BeginForm("RequestInsert", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "requestForm" }, new { id = "reqins" }))
The jQuery submit event handler on the host page:
$(document).on('submit', '#reqins', function (e) {
e.preventDefault();
let data = $("form :input").serializeArray();
$.ajax({
url: '#Url.Action("RequestInsert", "Home")'
,type: "POST"
,data: { "__RequestVerificationToken": token, "model": data }
})
.done(function (data) {
$("#requestForm").html("");
table.search('').columns().search('').draw();
})
.fail(function (jqXHR, textStatus) {
alert("fail");
});
});
I am a little confused with the partial view and ajax form.
Since your objective is checking validation status from AJAX response, you can use if condition against AJAX response as shown below:
$('#reqins').submit(function (e) {
e.preventDefault();
let data = $('form :input').serializeArray();
$.ajax({
url: '#Url.Action("RequestInsert", "Home")',
type: 'POST',
data: { "__RequestVerificationToken": token, "model": data },
success: function (result) {
// check valid response
if (result.invalid) {
$('#requestForm').html(result.form);
}
else {
$('#requestForm').html(result);
table.search('').columns().search('').draw();
}
},
error: function (jqXHR, textStatus) {
alert("fail");
}
});
});
Then inside controller action you can return both validation status and partial view using Controller.Json() with RenderViewToString() extension method provided here:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RequestInsert(ViewModel model)
{
// perform validation here
// assume IsValid is a boolean returned from validation status
if (IsValid)
{
// successful validation, return empty form
return PartialView("FormPartialView");
}
else
{
// validation failed, return failure status and previously-filled form
return Json(new { invalid = true, form = RenderViewToString(PartialView("FormPartialView", model)) });
}
}
try this and remove the Ajax Helper
$('#reqins').on('click', function () {
let data = $("form :input").serializeArray();
$.ajax({
url: '#Url.Action("RequestInsert", "Home")'
,type: "POST"
,data: data
,success:function (result) {
$("#requestForm").html(result);
}});
});
modify your action to this
public JsonResult RequestInsert()
{
try
{
return Json(new { success = true, result = PartialView("Prtialview") });
}
catch (Exception ex)
{
return Json(new { success = false, result = ex.ErrorMessage });
}
}
and then modify the client side as following
$('#reqins').on('click', function () {
let data = $("form :input").serializeArray();
$.ajax({
url: '#Url.Action("RequestInsert", "Home")'
,type: "POST"
,data: data
,success:function (result) {
if(result.succuss)
{
$("#requestForm").html(result);
}
else
{
alert("Error");
}
}});
});

jQuery Ajax call to controller

I'm new to Ajax and I'm trying to disable a checkbox if certain items are selected in a dropdown. I need to pass in the mlaId to the GetMlaDeliveryType(int Id) method in the RecipientsController.cs.
I'm not exactly sure how to set up the ajax call in the javascript function checkMlaDeliveryType(mlaId).
// MLA Add disable express checkbox if delivery type is electronic
$('.AddSelectedMla').change(function () {
var deliveryType = checkMlaDeliveryType($('.AddSelectedMla').val());
// disable express option if delivery type is Electronic
if (deliveryType == "Mail") {
$(".mlaExpressIndicator").removeAttr("disabled");
}else{
$(".mlaExpressIndicator").attr('checked', false).attr("disabled", true);
}
})
// ajax call to get delivery type - "Mail" or "Electronic"
function checkMlaDeliveryType(mlaId)
{
$.ajax({
type: "GET",
url: "/Recipients/GetMlaDeliveryType/" ,
data: mlaId,
dataType: ,
success:
});
}
RecipientsController.cs
public string GetMlaDeliveryType(int Id)
{
var recipientOrchestrator = new RecipientsOrchestrator();
// Returns string "Electronic" or "Mail"
return recipientOrchestrator.GetMlaDeliveryTypeById(Id);
}
EDIT:
Here's how the final javascript looked that worked
// MLA Add disable express checkbox if delivery type is electronic
$('.AddSelectedMla').change(function () {
checkMlaDeliveryType($('.AddSelectedMla').val());
})
// ajax call to get delivery type - "Mail" or "Electronic"
function checkMlaDeliveryType(mlaId)
{
$.ajax({
type: 'GET',
url: '#Url.Action("GetMlaDeliveryType", "Recipients")',
data: { id: mlaId },
cache: false,
success: function (result) {
// disable express option if delivery type is Electronic
if (result == "Mail") {
$(".mlaExpressIndicator").removeAttr("disabled");
} else {
$(".mlaExpressIndicator").attr('checked', false).attr("disabled", true);
}
}
});
}
$.ajax({
type: 'GET',
url: '/Recipients/GetMlaDeliveryType',
data: { id: mlaId },
cache: false,
success: function(result) {
}
});
then fix your controller action so that it returns an ActionResult, not a string. JSON would be appropriate in your case:
public string GetMlaDeliveryType(int Id)
{
var recipientOrchestrator = new RecipientsOrchestrator();
// Returns string "Electronic" or "Mail"
return Json(
recipientOrchestrator.GetMlaDeliveryTypeById(Id),
JsonRequestBehavior.AllowGet
);
}
Now your success callback will directly be passed a javascript instance of your model. You don't need to specify any dataType parameters:
success: function(result) {
// TODO: use the result here to do whatever you need to do
}
Set data in the Ajax call so that its key matches the parameter on the controller (that is, Id):
data: { Id: mlaId },
Note also that it's a better practice to use #Url.Action(actionName, controllerName) to get an Action URL:
url: '#Url.Action("GetMlaDeliveryType", "Recipients")'

how to return JSON with MVC Controller

I am calling my controller method using .ajax. my controller method call web service which returns dictionary.
now i need to return this and populate dropdown list. i am trying with return JSON and need to populate using success (response)
I am using MVC 1.0
$.ajax(
{
url: 'LookupValue/',
data: { 'sLookupIds': selectedtext },
datatype: "json",
traditional: true,
success: function (data) {
alert(data.value);
}
});
thanks in advance.
In controller
public JsonResult LookupValue(String sLookupIds)
{
SelectList olist = new SelectList(oDict, "key","value");
return Json(olist);
}
In view
$.ajax(
{
url: 'LookupValue/',
data: { 'sLookupIds': selectedtext },
datatype: "json",
traditional: true,
success: function (data) {
$.each(data, function (index, val) {
$('#lookup')
.append($("<option></option>")
.attr("value", val.Value)
.text(val.Text));
//ddHTML = ddHTML + "<option value='" + val.Value + "'>'" + val.Texts + "'</option>";
});
}
});
In your Action in your Controller:
return Json(data);
Where data is your object that you want serialiazed to JSON.
If you want to use Json.NET, just override the Json method.

How can I RedirectToAction within $.ajax callback?

I use $.ajax() to poll an action method every 5 seconds as follows:
$.ajax({
type: 'GET', url: '/MyController/IsReady/1',
dataType: 'json', success: function (xhr_data) {
if (xhr_data.active == 'pending') {
setTimeout(function () { ajaxRequest(); }, 5000);
}
}
});
and the ActionResult action:
public ActionResult IsReady(int id)
{
if(true)
{
return RedirectToAction("AnotherAction");
}
return Json("pending");
}
I had to change the action return type to ActionResult in order to use RedirectToAction (originally it was JsonResult and I was returning Json(new { active = 'active' };), but it looks to have trouble redirecting and rendering the new View from within the $.ajax() success callback. I need to redirect to "AnotherAction" from within this polling ajax postback. Firebug's response is the View from "AnotherAction", but it's not rendering.
You need to consume the result of your ajax request and use that to run javascript to manually update window.location yourself. For example, something like:
// Your ajax callback:
function(result) {
if (result.redirectUrl != null) {
window.location = result.redirectUrl;
}
}
Where "result" is the argument passed to you by jQuery's ajax method after completion of the ajax request. (And to generate the URL itself, use UrlHelper.GenerateUrl, which is an MVC helper that creates URLs based off of actions/controllers/etc.)
I know this is a super old article but after scouring the web this was still the top answer on Google, and I ended up using a different solution. If you want to use a pure RedirectToAction this works as well. The RedirectToAction response contains the complete markup for the view.
C#:
return RedirectToAction("Action", "Controller", new { myRouteValue = foo});
JS:
$.ajax({
type: "POST",
url: "./PostController/PostAction",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (result) {
if (result.responseText) {
$('body').html(result.responseText);
}
}
});
C# worked well
I just changed the JS because responseText was not working for me:
$.ajax({
type: "POST",
url: posturl,
contentType: false,
processData: false,
async: false,
data: requestjson,
success: function(result) {
if (result) {
$('body').html(result);
}
},
error: function (xhr, status, p3, p4){
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
You could use the Html.RenderAction helper in a View:
public ActionResult IsReady(int id)
{
if(true)
{
ViewBag.Action = "AnotherAction";
return PartialView("_AjaxRedirect");
}
return Json("pending");
}
And in the "_AjaxRedirect" partial view:
#{
string action = ViewBag.ActionName;
Html.RenderAction(action);
}
Reference:
https://stackoverflow.com/a/49137153/150342

Resources