Currently autocomplete is firing, returning empty rows under the textbox.
Empty Rows shown under textbox.
How to get return json values into search textbox?
I need to add more details to get this form to submit.
View
<input type="text" class="sicautocomplete" placeholder="search by SIC Code" />
Controller:
public JsonResult SICCodeSearch(string term)
{
var siccodes = LogicEngineLifetime.Database.SICCodes
.Where(s => s.Code.ToString()
.Contains(term))
.Distinct()
.Select(x => x.Code)
.Take(100)
.ToList();
return Json(siccodes, JsonRequestBehavior.AllowGet);
}
JS:
$(".sicautocomplete").autocomplete({
minLength: 2,
source: function(request, response) {
jQuery.get(sicCodesURL, { term: request.term }, function (data) {
// assuming data is a JavaScript array such as
// ["one#abc.de", "onf#abc.de","ong#abc.de"]
// and not a string
response(data);
});
},
focus: function(event, ui) {
return false;
},
change: function(event, ui) {
if (!ui.item)
$(this).val('');
},
select: function(event, ui) {
var a = ui.item;
$(".sicautocomplete").val("");
return false;
}
});
//$(".sicautocomplete").autocomplete("instance")._renderItem = function (ul, c) {
// return $("<li></li>")
// .data("item.autocomplete", c)
// .append(c)
// .appendTo(ul);
//};
Related
I tried to use reactjs work with C# MVC, and i want to use reactjs ajax to get json array from controller,then show the array elements into select options. But if i use local array, it could show in the select options. I can print out the array element when i use ajax query server method. I do not what happenend.
My view:
<div class="col-md-12">
<div class="col-md-2" id="select">
</div>
</div>
<script type="text/babel">
var Groups = React.createClass({
getInitialState: function () {
return {
data: []
};
},
componentDidMount: function(){
this.serverRequest = $.get(this.props.rout, function(response){
this.setState({
data: response
});
}.bind(this));
},
componentWillUnmount: function(){
this.serverRequest.abort();
},
render () {
return (<select className="selectpicker" multiple="multiple" title="Choose 2-4 colors" data-live-search="true">
{this.state.data.map(function (x) {
console.log(x);
return <ABC value={x} />;
})}
</select>);
}
});
var ABC = React.createClass({
render: function(){
console.log("Option");
console.log(this.props.value);
return <option value={this.props.value}>{this.props.value}</option>;
}
});
ReactDOM.render(
<Groups rout="/CodingManagement/Notification/GroupName" />,
document.getElementById('select')
)
</script>
I could see the console result, but it does not show in view. But if i pass the array to {data}, it could show in the view.
Like this one, it works. I do not know why
<script type="text/babel">
var Groups = React.createClass({
getInitialState: function () {
return {
data: this.props.rout
};
},
render () {
console.log("Groups");
console.log(this.state.data);
return (<select className="selectpicker" multiple="multiple" title="Choose 2-4 colors"
data-live-search="true">
{this.state.data.map(function (x) {
return <ABC value={x}/>;
})}
</select>);
}
});
var ABC = React.createClass({
render: function () {
console.log("Option");
console.log(this.props.value);
return (
<option value={this.props.value}>{this.props.value}</option>
);
}
});
ReactDOM.render(
<Groups rout={["Group4", "Group1", "Group11"]}/>
,
document.getElementById('select')
);
This is server code
public JsonResult GroupName()
{
string[] group = new string[] { "Group4", "Group2", "Group3" };
return Json(group, JsonRequestBehavior.AllowGet);
}
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);
}
So basically I'm creating a Request system in a MVC application. I have this "Create Request" section where I can select the type of request I want to do in a DropDownList from Telerik. What I want to do is, every time I choose something from the list, a partial view appears with the form related to that type of request.
This is my ajax Post from the Create.cshtml View:
<script>
function change() {
var value = $("#RequestType").val();
alert(value);
$.ajax({
url: "/Request/CreateRequestForm",
type: "get",
data: { requestValue : JSON.stringify(value)}
}).done(function (data) {
$("#partialplaceholder").html(data);
}).fail(function () {
alert('error');
})
};
</script>
This is my controller:
public ActionResult Index()
{
//Things
return View();
}
[HttpGet]
public ActionResult Create()
{
return View();
}
[HttpGet]
public PartialViewResult CreateRequestForm(string dropDownValue)
{ string partialView="";
int RequestType = Convert.ToInt32(dropDownValue);
switch (RequestType)
{
case 1 :
partialView+="_CreateAbsence";
break;
case 2 :
partialView += "_CreateAdditionalHours";
break;
case 3 :
partialView += "_CreateCompensationDay";
break;
case 4 :
partialView += "_CreateErrorCorrection";
break;
case 5 :
partialView += "_CreateVacation";
break;
}
return this.PartialView(partialView);
}
Everytime time the even triggers my dropDownValue string is null... Why? Thanks in advance! :)
EDIT
View Code
<h1>Create New Request</h1>
#(Html.Kendo().DropDownList()
.Name("RequestType")
.DataTextField("Text")
.DataValueField("Value")
.Events(e => e.Change("change"))
.BindTo(new List<SelectListItem>() {
new SelectListItem() {
Text = "Absence",
Value = "1"
},
new SelectListItem() {
Text = "Additional Hours",
Value = "2"
},
new SelectListItem() {
Text = "Compensation Day",
Value = "3"
},
new SelectListItem() {
Text = "Error Correction",
Value = "4"
},
new SelectListItem() {
Text = "Vacation",
Value = "5"
}
})
.Value("1")
)
<script>
function change() {
var value = $("#RequestType").val();
alert(value);
$.ajax({
url: "/Request/CreateRequestForm",
type: "get",
data: { requestValue : JSON.stringify(value)}
}).done(function (data) {
$("#partialplaceholder").html(data);
}).fail(function () {
alert('error');
})
};
</script>
<div id="partialplaceholder">
</div>
First of all: The title says you're doing a post request but in your code there's a get request.
Second: In order to make it work you have to change either the name of the data in the javascript you're sending to match the parameter name in the c# code like:
<script>
function change() {
var value = $("#RequestType").val();
alert(value);
$.ajax({
url: "/Request/CreateRequestForm",
type: "get",
data: { dropDownValue: JSON.stringify(value)}
}).done(function (data) {
$("#partialplaceholder").html(data);
}).fail(function () {
alert('error');
})
};
</script>
or change the name of the parameter in the c# method, like:
[HttpGet]
public PartialViewResult CreateRequestForm(string requestValue )
{
...
}
Third: I'm quite sure you don't need to JSON.Stringify() the data. For more details about the Stringify() method & usages please check this link
I am trying to assign value to select2 control from a hiddenfield in clientside script. Value is not assigned to select2 control after postback for the following code.
$(document).ready(function () {
$("#cboIndustry").select2();
$.getJSON(uriSector+ '/' + 'GetIndustrySectors')
.done(function (data) {
$.each(data, function (key, item) {
$("#cboIndustry").append($("<option></option>").val(item.IndustrySectorID).html(item.IndustrySectorName));
});
});
$("#cboIndustry").on('change', function () {
if ($("#cboIndustry").val() != "-1") {
var id = $("#cboIndustry").val();
$('#HiddenIndustrySectorID').val(id);
SelectedName = $('#cboIndustry option:selected').text();
$('#HiddenIndustrySectorName').val(SelectedName);
}
});
var SelectedIndustry = $('#HiddenIndustrySectorID').val();
$("#cboIndustry").select2().select('val',SelectedIndustry);
});
However value get assigned if I put alert before assigning
var SelectedIndustry = $('#HiddenIndustrySectorID').val();
alert(SelectedIndustry);
$("#cboIndustry").select2().select('val',SelectedIndustry);
// These steps I have included, for retaining value in select2 on postback.
What could be the reason? Please help me.
Why don't use this line
$("#cboIndustry").select2().val(SelectedIndustry);
BTW i have not tested
$('#HiddenIndustrySectorID').val(id);
Change this line to
document.getElementById("HiddenIndustrySectorID").value =id;
and try
$(document).ready(function () {
$("#cboIndustry").select2();
$.getJSON(uriSector+ '/' + 'GetIndustrySectors')
.done(function (data) {
$.each(data, function (key, item) {
$("#cboIndustry").append($("<option></option>").val(item.IndustrySectorID).html(item.IndustrySectorName));
});
//This change solves my problem
var SelectedIndustry = $('#HiddenIndustrySectorID').val();
$("#cboIndustry").select2().select('val',SelectedIndustry);
});
$("#cboIndustry").on('change', function () {
if ($("#cboIndustry").val() != "-1") {
var id = $("#cboIndustry").val();
$('#HiddenIndustrySectorID').val(id);
SelectedName = $('#cboIndustry option:selected').text();
$('#HiddenIndustrySectorName').val(SelectedName);
}
});
});
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).