How to get the Json Value correctly? - c#

I am having a HttpPost request sending back an object Value.
I would like to make the ComputerLocation div appear when the object Value is true(s.IsComputer is a bool).
Currently nothing happens.
I tried to debug it using Firebug and verified that actually the request posts back the object Value:true, but when i check my result.Value, Value is shown as undefined.
Please check what I am doing wrong?
Script:
<script type='text/javascript'>
$(document).ready(function () {
$('#typeddl').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#typeddl').val() },
success: function (result) {
$('#ComputerLocation').toggle(result.Value === true);
}
});
});
$('#typeddl').trigger('change');
});
</script>
Json:
[HttpPost]
public JsonResult GetItemTypeForm(int itemTypeId)
{
//pseudo code
var data = from s in db.ItemTypes.ToList()
where s.ItemTypeId == itemTypeId
select new { Value = s.IsComputer };
return Json(data);
}

Use First method to get single result, because your query returns an IQueryable<T>
var data = (from s in db.ItemTypes.ToList()
where s.ItemTypeId == itemTypeId
select new { Value = s.IsComputer }).First();
Then return your result like this:
return Json( new { Value = data.Value });

Related

How to pass data to ajax function with json?

I need to get an id from the URL , comment value from textbox, save it to database and show on page with ajax.
Im not sure how should look correct syntax in my controller and ajax function.
Controller
[HttpPost]
public JsonResult AddComment(int id, string comment)
{
if (ModelState.IsValid)
{
return Json(true); // what should be here
}
return Json(true);
}
Ajax
$('#submit').click(function () {
$.ajax({
url: '/Form/AddComment',
method: 'POST',
data: {
id: 4, //how to get id from url?
comment: 'test' //how to get textbox value?
},
success: function (data) {
console.log(data)
},
error: function (a, b, c) {
console.log('err')
}
})
});
this just show me that it work but i dont know how to move forward
Based upon your requirement, you would have to do the appropriate form handling at client side in order to get your variables like id and comment. You can use strongly typed model binding to get your form values and process them on submit or you can use JavaScript techniques to process your form variables. To extract out id from a URL, you can use a Regular Expression or other JavaScript string parsing techniques. I am giving you a simple example of getting your id from a URL and comment from a text box using JavaScript:
Your input control would look like:
<input type="text" id="commentBox" name="Comment" class="form-control" />
In order to achieve your desired functionality using AJAX to POST your form variables to controller, refer to the following code snippet:
AJAX:
<script type="text/javascript">
var url = 'http://www.example.com/4'; //Example URL string
var yourid = url.substring(url.lastIndexOf('/') + 1);
var yourcomment= document.getElementById('commentBox').value;
var json = {
id: yourid, //4
comment: yourcomment
};
$('#submit').click(function (){
$.ajax({
url: '#Url.Action("AddComment", "Form")',
type: "POST",
dataType: "json",
data: { "json": JSON.stringify(json)},
success: function (data) {
console.log(data)
},
error: function (data) {
console.log('err')
},
});
};
</script>
And you can get your values in your Controller like this:
using System.Web.Script.Serialization;
[HttpPost]
public JsonResult AddComment(string json)
{
if (ModelState.IsValid)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
string id= jsondata["id"];
string comment=jsondata["comment"];
// Do something here with your variables.
}
return Json(true);
}
My solution looks like this:
controller:
[HttpPost]
public JsonResult AddComment(int id_usr,string comment)
{
if (ModelState.IsValid)
{
Comments kom = new Comments();
kom.DateComment = DateTime.Now;
kom.Id_usr = id_usr;
kom.Comment = comment;
db.Comments.Add(kom);
db.SaveChanges();
return Json(kom);
}
return Json(null);
}
View
var url = window.location.pathname;
var idurl = url.substring(url.lastIndexOf('/') + 1);
$('#submit').click(function () {
console.log('click')
$.ajax({
url: '/form/AddComment',
method: 'POST',
data: {
comment: $("#Comments_Comment").val(),
id_usr: idurl,
},
success: function (data) {
console.log(data),
thank you all for guiding me to the solution

MVC Droplist to trigger controller to get data to populate another droplist

We were able to do this with Angular, but are trying to do this with MVC using C# and Razor and possibly jQuery if need be.
What we are trying to do is, we populate a dropdown list with data already populated. (done). In our View we put an onChange event in which we then want to trigger another method in the controller so that we may get another list of items to populate the next droplist.
IN doing some VERY simple examples,we keep either getting a 404 or 500 return in our browser console and not hitting any breakpoints in Visual Studio.
This is what I have so far:
View
<div> #Html.DropDownListFor(model => model.Name, Model.AvailableGalaxyEventTypes, new { #id = "eventTypeName", onchange = "GetEventNames();" })
</div>
<script>
function GetEventNames() {
var url = '#Url.Action("GetData")';
var strId = 0;
$.ajax({
url: url,
type: 'GET',
cache: false,
data: { value: strId },
success: function (result) {
alert(result);
console.log(result);
$('#result').html(result);
}
});
}
</script>
Controller
public ActionResult GetData(string id)
{
return Json(new { foo = "bar", ball = "dragon" });
}
I don't understand why we are not getting a success or anything back doing this very simple example. I should get Foo and Ball back. If we could get to the controller method, we should be able to make headway but I am getting 404 or 500 now.
Any ideas?
your method is accepting parameter id but you are passing value as parameter in ajax request
data: { id: strId }
or try by specifying controller name as well as action method name explicitly
url: '#Url.Action("Foo", "SomeController")',
#Html.DropDownListFor(model => model.CountryId, Model.AvailableCountries)
#Html.DropDownListFor(model => model.RegionId, Model.AvailableRegions)
$("##Html.FieldIdFor(model => model.CountryId)").change(function () {
var selectedItem = $(this).val();
var ddlRegions = $("##Html.FieldIdFor(model => model.RegionId)");
$.ajax({
cache: false,
type: "GET",
url: "#(Url.RouteUrl("GetRegionsByCountryId"))",
data: { "countryId": selectedItem, "addSelectStateItem": "true" },
success: function (data) {
ddlRegions.html('');
$.each(data, function (id, option) {
ddlRegions.append($('<option></option>').val(option.id).html(option.name));
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve regions.');
}
});
And extension method that gets Id of DDL (or you can do it using JQuery or Vanilla JS):
public static string FieldIdFor<T, TResult>(this HtmlHelper<T> html, Expression<Func<T, TResult>> expression)
{
var id = html.ViewData.TemplateInfo.GetFullHtmlFieldId(ExpressionHelper.GetExpressionText(expression));
// because "[" and "]" aren't replaced with "_" in GetFullHtmlFieldId
return id.Replace('[', '_').Replace(']', '_');
}
And method in controller:
public ActionResult GetRegionsByCountryId(string countryId)
{
var country = _countryService.GetCountryById(Convert.ToInt32(countryId));
var states = _stateProvinceService.GetStateProvinces(country != null ? country.Id : 0).ToList();
var result = (from s in states
select new {id = s.Id, name = s.Title})
.ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}

Microsoft JScript runtime error: Object doesn't support property or method 'val'

I am making a json request and i want a specific div to appear if the result from the request is true.
Currently I am getting the error bellow , could you please help me with the solution ?
Microsoft JScript runtime error: Object doesn't support property or
method 'val'
p.s : I have checked through console that json returns correctly "true" and the issue is on success.
I am attaching the code bellow.
Script :
<script type='text/javascript'>
$(document).ready(function () {
$('#ComputerLocation').hide();
$('#typeddl').on('change', function () {
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#typeddl').val() },
success: function (result) {
if (result != null && result.val(this.Value) == 'true') {
$('#ComputerLocation').show();
};
}
});
});
});
</script>
Controller:
[HttpPost]
public JsonResult GetItemTypeForm(int itemTypeId)
{
//pseudo code
var data = from s in db.ItemTypes
where s.ItemTypeId == itemTypeId
select new { Value = s.IsComputer };
return Json(data);
}
if I understood correctly :
When you try to get val() in this line
(ifresult != null && result.val(this.Value) == 'true') {
you are assuming result has a function called val, but in json you cant send function and you are trying to send this function this.Value and that really don't make any sense at all.
I assume you want to :
if (result != null && result.val == 'true') {
and in this line also you are using this I think that might also be wrong. You should set this to another field before using in ajax callback.
<script type='text/javascript'>
$(document).ready(function () {
$('#ComputerLocation').hide();
$('#typeddl').on('change', function () {
var that = this; // now this is an jquery object
$.ajax({
type: 'POST',
url: '#Url.Action("GetItemTypeForm")',
data: { itemTypeId: $('#typeddl').val() },
success: function (result) {
if (result != null && result.val == 'true') { // maybe you want to check that.val()
$('#ComputerLocation').show();
};
}
});
});
});

How to get the data from json to MVC4 c#?

I have a MVC4 single page website with a form. The loading of the contents is achieve with ajax. I do not know how to get the data out from JSON in C#? Here is my code:
JavaScript:
$("#subnt").click(function (event) {
event.preventDefault();
var url = "/Home/Submit";
$.post(url, $('form[name="cnt_us-frm"]').serialize(), function (data) {
if (data.Success === true) {
$("#min-content").hide().load("/Home/PartialSubmit").fadeIn('normal'); // loads the page into 'min-content' section
}
else {
// display error message
}
})
});
});
C#:
[HttpPost]
public JsonResult Submit()
{
return Json(new { Success = true, SomeOtherData = "testing" });
}
Please check below working code -
I have used exactly your working code -
[HttpPost]
public JsonResult Submit()
{
return Json(new { Success = true, SomeOtherData = "testing" });
}
Then I used following JQuery to hit the above action -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$('#click').click(function (e) {
$.ajax({
url: "#Url.Action("Submit")",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response);
},
success: function (data) {
if (data.Success == true)
alert(data.SomeOtherData);
}
});
});
});
</script>
<input type="submit" value="click" id="click" />
And as the output I was able to get an alert as shown below -
Easiest thing to do is use the superior json.net
[HttpPost]
public string Submit()
{
var result = new { success = true, someOtherDate = "testing"};
var json = JsonConvert.SerializeObject(result);
return json;
}
Your code is ok bu you can add debugger.and open developer tools check your data .
$.post(url, $('form[name="cnt_us-frm"]').serialize(), function (data) {
debugger;
if (data.Success === true) {
$("#min-content").hide().load("/Home/PartialSubmit").fadeIn('normal'); // loads the page into 'min-content' section
}
else {
// display error message
}
No, the other way around. How to retrieve the data from the form (json).

Autocomplete: display results with json data

I am trying to build an autocomplete, but I have troubles patching along the parts.
First, my view include this field:
<p>#Html.TextBoxFor(_item => _item.mCardName, Model.mCardName, new { #class = "cardText", id = "card_name"} ) </p>
Very simple. Next, the javascript call:
<script type="text/javascript">
$(function() {
$('#card_name').autocomplete({
minlength: 5,
source: "#Url.Action("ListNames", "Card")",
select: function (event, ui) {
$('#card_name').text(ui.item.value);
},
});
});
</script>
Which calls this method:
public ActionResult ListNames(string _term)
{
using (BlueBerry_MTGEntities db = new BlueBerry_MTGEntities())
{
db.Database.Connection.Open();
var results = (from c in db.CARD
where c.CARD_NAME.ToLower().StartsWith(_term.ToLower())
select new {c.CARD_NAME}).Distinct().ToList();
JsonResult result = Json(results.ToList(), JsonRequestBehavior.AllowGet);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
If i insert the "Power" word, the JSON data is posted back like this:
{"ContentEncoding":null,"ContentType":null,"Data":[{"CARD_NAME":"Power Armor"},{"CARD_NAME":"Power Armor (Foil)"},{"CARD_NAME":"Power Artifact"},{"CARD_NAME":"Power Conduit"},{"CARD_NAME":"Power Conduit (Foil)"},{"CARD_NAME":"Power Leak"},{"CARD_NAME":"Power Matrix"},{"CARD_NAME":"Power Matrix (Foil)"},{"CARD_NAME":"Power of Fire"},{"CARD_NAME":"Power of Fire (Foil)"},{"CARD_NAME":"Power Sink"},{"CARD_NAME":"Power Sink (Foil)"},{"CARD_NAME":"Power Surge"},{"CARD_NAME":"Power Taint"},{"CARD_NAME":"Powerleech"},{"CARD_NAME":"Powerstone Minefield"},{"CARD_NAME":"Powerstone Minefield (Foil)"}],"JsonRequestBehavior":0,"MaxJsonLength":null,"RecursionLimit":null}
For reference purpose, here are two of the scripts that run:
<script src="/Scripts/jquery-2.0.3.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
However nothing is displayed. I would have liked to see the results displayed like a normal autocomplete would do. Can anyone help me out making things work?
EDIT
I have been working on this for a while. I have posted up there the new javascript, controller method and results obtained. But the thing still does not work and I would appreciate any help.
for autocompletes, i use the javascriptserializer class. the code goes something like this.
My.Response.ContentType = "application/json"
Dim serializer As JavaScriptSerializer = New JavaScriptSerializer
Dim dt As DataTable = GetDataTable("proc_name", My.Request.QueryString("term"))
Dim orgArray As ArrayList = New ArrayList
For Each row As DataRow In dt.Rows
Dim thisorg As New thisOrg
thisorg.id = row("organization_child_id")
thisorg.value = row("organization_name")
orgArray.Add(thisorg)
Next
My.Response.Write(serializer.Serialize(orgArray))
Public Class thisOrg
Public id As Integer
Public value As String
End Class
basically just takes a datatable, adds a series of objects to the array, then serializes it.
Finally! After taking a break, I got my answer.
See this?
public ActionResult ListNames(string _term)
{
using (BlueBerry_MTGEntities db = new BlueBerry_MTGEntities())
{
db.Database.Connection.Open();
var results = (from c in db.CARD
where c.CARD_NAME.ToLower().StartsWith(_term.ToLower())
select new {c.CARD_NAME}).Distinct().ToList();
JsonResult result = Json(results.ToList(), JsonRequestBehavior.AllowGet);
return Json(result, JsonRequestBehavior.AllowGet);
}
}
As it happens, I was building a Json object OF another Json object. So that's why the data was not passed properly.
I've rebuilt the method, made it work, and refined it like this:
public JsonResult ListCardNames(string term)
{
using (BlueBerry_MagicEntities db = new BlueBerry_MagicEntities())
{
db.Database.Connection.Open();
var results = from cards in db.V_ITEM_LISTING
where cards.CARD_NAME.ToLower().StartsWith(term.ToLower())
select cards.CARD_NAME + " - " + cards.CARD_SET_NAME;
JsonResult result = Json(results.ToList(), JsonRequestBehavior.AllowGet);
return result;
}
And my javascript action:
<script type="text/javascript">
$(function() {
$('#searchBox').autocomplete({
source: function(request, response) {
$.ajax({
url: "#Url.Action("ListCardNames")",
type: "GET",
dataType: "json",
data: { term: request.term },
success: function(data) {
response($.map(data, function(item) {
return { label: item, value1: item };
}));
}
});
},
select:
function(event, ui) {
$('#searchBox').val(ui.item);
$('#cardNameValue').val(ui.item);
return false;
},
minLength: 4
});
});
</script>
And now everything works like a charm.

Categories

Resources