Script doesnt connect to JsonResult Controller - c#

I have a problem with connecting the script with the autocomplete function to my Json controller. The view is a formula, where the user can insert data, like dates with the datepicker function and general text to describe the issues. The whole formula is in this:
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
All Textboxes, DropDownLists and Editors are connected to the model like so:
<div class="editor-label">
#Html.LabelFor(model => model.Overview)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Overview)
#Html.ValidationMessageFor(model => model.Overview)
</div>
At the moment I try to insert the Textbox, where the autocomplete should happen like this:
<b>Name: </b>
#Html.TextBox("searchTerm", null, new { id = "txtSearch" })
The txtSearch is connected to my skript SearchUser.js:
$(function () {
$("#txtSearch").autocomplete({
source: '#url.Action("New1", "Dialog")',
minLength: 1
});
});
when I use a source an array of strings, the autocomplete appears.
the JavaScript is registered on top of the view and jQueryUI is registered in _Layout.cshtml. I am using jquery 1.11.3 and jqueryui 1.11.4 .
In The Controller New1 in the JsonResult you find this:
public JsonResult Dialog(string search)
{
List<string> users = db
.Users
.Where(p => p.FirstName.ToLower().Contains(search.ToLower()))
.Select(p => p.LastName)
.ToList();
return Json(users, JsonRequestBehavior.AllowGet);
}
when i test the website and look for http://localhost:51299/New1/Dialog?search=m
i get the json file. The json file contains this: ["Mueller"]
But when I go to my formula http://localhost:51299/New1/Create and insert "m" into the TextBox nothing happens.
So now my question: What can i do to make it work?
Update (It's working!!!)
Aaaaah its working!!!. Thanks a lot! He couldnt use the source, so now I changed it to "/New1/Dialog".
I know it is not a good way to use the direct url instead of '#url.Action("Dialog", "New1")', but i think he couldnt differ between normal ' and ".
If you have an Idea why i couldnt use #url.Action, i would be interested in it.
View (Create.cshtml)
#Html.TextBox("searchTerm", null, new { id = "searchTerm" })
Skript (SearchUser.js)
$(function () {
$("#searchTerm").autocomplete({
source: "/New1/Dialog",
minLength: 1
});
});
controller (New1Controller.cs)
public JsonResult Dialog(string term)
{
List<string> users = db
.Users
.Where(p => p.LastName.ToLower().Contains(term.ToLower()))
.Select(x => x.LastName)
.ToList();
return Json(users, JsonRequestBehavior.AllowGet);
}

jQueryUI autocomplete is using the name term (not search) to craft a request. In other words, when you type "m", it's sending the following request:
http://localhost:51299/New1/Dialog?term=m
You should be able to fix this by simply renaming the parameter:
public JsonResult Dialog(string term)

Related

Asp.Net MVC Get value from Dropdownlist to PartialView

In my main page I have Dropdownlist of Cars. And it works fine.
And When I select one car from Dropdownlist I want to get back all car modells who belongs to the selected Car from Dropdownlist in the same view, let say under Dropdownlist. DropDownlist with Cars and Models of the selected cars in the same View (in Main view). I tried with PartialView but I'am not so good when it comes PartielView and html code
This is my action to get CarModels, and I think this must be as PartialView
[HttpGet]
public ActionResult GetCarModel(int? carId)
{
List<CarModelVW> listOfCarModel;
using (Db db = new Db())
{
listOfCarModel = db.CarModel.ToArray()
.Where(x => carId == null || carId == 0 || x.carId == carId)
.Select(x => new CarModelVW(x))
.ToList();
}
return View(listOfCarModel);
}
In my Main View with DropDownlist
<div class="form-group">
<label class="control-label col-md-2" for="HasSidebar"> Car </label>
<div class="col-md-10">
#Html.DropDownListFor(model => model.CarId, Model.Cars, "---Select car---", new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.CarId, "", new { #class = "text-danger" })
</div>
</div>
And here below Dropdownlist I want to get all carmodels of selected car
But I think I have to create <div> </div> with Id or span .. but I'am not sure how to do here.
And here is javascript I'am trying to use
$("#CarId").change(function () {
var carId = $(this).val();
if (carId) {
window.location = "/an/GetCarModel?carId=" + carId;
}
return false;
});
How do I get this action GetCarModel below Dropdownlist view? Thank you in advance.
Just like Roman said, instead of navigating to the url, you should send an ajax call to the control.
First of all, add an id to your dropdownlist.
Secondly, in the Onchange function add an ajax call to get cars:
var dropdownval = $("#//Id of dropdown").val();
var json = '{Id: ' + dropdownval + '}';
$.ajax({
url:'#Url.Action("GetCarModel", "//The controller")',
type:'POST',
data: json,
contentType:'Application/json',
success:function(result){
//Do whatever
}
})
You can then do whatever with the result you pass back to the ajax call
If you want to view results on the same page then you need to use Ajax.
add this div tag Main view where you want to display results:
<div id="carmodels"></div>
Change your jquery function as below:
$("#CarId").change(function () {
var carId = $(this).val();
if (carId)
{
$.get("/an/GetCarModel?carId=" + carId, function(data){
$("#carmodels").html(data);
});
}
});

MVC (Razor) Filter DropDownList

I'm new to MVC and JavaScript and I have a question about DropDownList.
I Build a program of "Car Renting" and I have a View that allow adding new Car to the inventory.
The view include 2 dropdownlists (see below):
<div class="editor-field">
#Html.DropDownList("ManufacturerId", string.Empty)
#Html.ValidationMessageFor(model => model.ManufacturerId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ModelId)
</div>
<div class="editor-field">
#Html.DropDownList("ModelId", string.Empty)
#Html.ValidationMessageFor(model => model.ModelId)
</div>
I want that when user select a manufacturer for example (Alfa Romeo) the "model" list box will display only "Alfa Mito" models and not the full list...
My Controller function send to the view the Model List using ViewBag see below:
public ActionResult AddNewCar()
{
ViewBag.ManufacturerId = new SelectList(db.Manufacturers, "ManufacturerId", "ManufacturerName");
ViewBag.ModelId = new SelectList(db.Models, "ModelId", "ModelName");
ViewBag.BranchId = new SelectList(db.Branchs, "BranchId", "BranchName");
return View();
}
Please advice.
Thanks,
Almog
call below action method from jquery on dropdown change event.
public List<carmodels> PopulateState(int manufacturerId)
{
var carmodelsObj = (from st in dc.Carmodels
where st.manufacturerId.Equals(manufacturerId)
select st).ToList();
return (carmodelsObj);
}
You need to repopulate/populate your ModelId dropdown on every time when your first dropdown changes (using jquery). Do following:
Get the ManufactureId from first dropdown on change event. and place an ajax call to repopulate your second dropdown.
$("#ManufactureId").change(function() {
var manufacturerId = manufacturer$('#ManufacturerId').val();
$.ajax({url: "~/Car/GetCarsByManufacturer", success: function(result){
//re populate your second dropdown here
//hint: you may use response.id for value
}});
});
Create a function in your controller that returns Car Models, based on selected. (call this function in previous step using ajax).
public List<carmodels> GetCarsByManufacturer(int manufacturerId)
{
var carmodelsObj = (from st in dc.Carmodels
where st.manufacturerId.Equals(manufacturerId)
select st).ToList();
return (carmodelsObj);
}

Cascading Dropdown MVC3 returning empty dropdown fields

I am attempting to create a cascading dropdown with MVC3. The parent dropdown is called "Category", when the user selects a Category, a child dropdown is then populated with a list of pictures that belong to that Category. I've got some code in place right now, and I am able to call the controller from the View when the user selects a category. Here is my code:
Controller:
public ActionResult Pictures(int catId)
{
var k = ((List<Picture>) ViewBag.AllPictures)
.FindAll(x => x.CategoryId == catId)
.Select(x => new
{
Value = x.PictureId,
Text = x.Title
});
return Json(k, JsonRequestBehavior.AllowGet);
}
View:
<div class="editor-field">
#Html.DropDownListFor(model => model.Picture.PictureId, Enumerable.Empty<SelectListItem>(), new { #id = "pictureFilter" })
#Html.ValidationMessageFor(model => model.Picture.PictureId)
</div>
Javascript:
<script type="text/javascript">
$('#ddlFilter').on("change", function() {
var selectedCat = $(this).val();
$.getJSON("/StoreManager/Pictures", { catId: selectedCat }, function(pictures) {
var picturesSelect = $('#pictureFilter');
picturesSelect.empty();
$.each(pictures, function(index, picture) {
picturesSelect.append($('<option/>', {
value: picture.val,
text: picture.text
}));
});
});
});
</script>
When I take a look at variable 'k', that my controller is returning. It does contain all the correct collection items for the pictures, with their respective 'value' and 'text' fields assigned. When it returns the JSON back to the View, it creates a dropdown menu with the exact number of fields that should be there, but they all contain empty data. When I inspect the element in Chrome, here is the HTML afterwards:
<option><option/>
<option><option/>
<option><option/>
<option><option/>
All help is appreciated. Any further code requested will be linked to in pastebin posts.
You have return JSON then you need to used same variables as you send from Pictures controller.
try this:
<script type="text/javascript">
$('#ddlFilter').on("change", function() {
var selectedCat = $(this).val();
$.getJSON("/StoreManager/Pictures", { catId: selectedCat }, function(pictures) {
var picturesSelect = $('#pictureFilter');
picturesSelect.empty();
$.each(pictures, function(index, picture) {
picturesSelect.append($('<option/>', {
value: picture.Value,
text: picture.Text
}));
});
});
});
</script>
or you can also check the response variable get from your Action method by using firebug console tab.

C# DropDown List default value

I am using this code to input values from a database table to a dropdown list:
<div class="editor-field">
#Html.DropDownListFor(model => model.TourImageID, new SelectList(Model.Images, "ImageID", "Filename", Model.TourImageID))
</div>
What i am trying to do is add an item to the top of the list, that is not present in the database table.
Something like DROPDOWN LIST VALUES = (DEFAULT-ITEM) + (DATABASE-TABLE-ITEMS)
is that possible? if so, how?
If your Model.Images is of type SelectList, you can do something like this in your controller:
var query = UnitOfWork.GlobalImageLibraryRepository.Images.Select(x => new { x.ImageID, x.Filename });
viewModel.Images = new SelectList(query.AsEnumerable(), "ImageID", "Filename");
viewModel.Images.Insert(0, new SelectListItem { Value = "0", Text = "--Select--" });
I've assumed that you have a method in your GlobalImageLibraryRepository class that returns IQueryable<Images> like this:
public IQueryable<Images> Images { get { return dbcontext.Images; } }
So after all that, your view will look like this:
<div class="editor-field">
#Html.DropDownListFor(model => model.TourImageID, (SelectList)Model.Images, Model.TourImageID))
</div>

Listbox html helper returning zero objects to Post function

I trying to get a listbox for a module I've created to work. The selector works (the titles of the selectable entities appear but there is no data returned to the Post function in the controller.
I don't know what you would need to be able to help me, but here is at least the html code.
HTML code:
<div class="field required">
#Html.LabelFor(model => model.Sessions)
#Html.ListBox("Sessions", new SelectList(Model.Sessions, "Id", "Title", 1));
#Html.ValidationMessageFor(model => model.Sessions)
</div>
Use ViewBag in Controller
ViewBag.Sessions = new SelectList(EntityName, "Id", "Name", entity.ID);
entity.ID will be value which you want to select
#Html.DropDownList("Sessions", "Select Sessions")

Categories

Resources