I am showing a number of flights in a view. I have created a button for every flight. On clicking this button I am getting the details of a single flight shown in the view.
here is my view code:
foreach (var item in Model)
{
<div class="toFrom">
<h3 id="FCity_#item.FlightID">#item.FromCity </h3>
<span><i class="fa mx-4 fa-plane"></i></span>
<h3 id="TCity_#item.FlightID">#item.ToCity</h3>
</div>
<div class="info d-flex">
<p class="me-2 " id="DDate_#item.FlightID">#item.DepartureDate.ToShortDateString()</p>
<p class="me-2" id="DTime_#item.FlightID">#item.DepartureTime.ToShortTimeString()</p>
<p class="me-2 " id="ATime_#item.FlightID">#item.ArrivalTime.ToShortTimeString()</p>
<select id="CFare_#item.Fare" class="form-control me-2">
#foreach (var re in ddlcabin)
{
<option value="#re.Fare">#re.CabinName (#re.Fare)</option>
}
</select>
<button class="form-control btn btn-primary" onclick="Save(#item.FlightID,#item.Fare)">select </button>
</div>
}
Now I want to get these values using and pass them to an action method without using a form in the view.
here is my js code:
function Save(id, fare) {
var fct = $("#FCity_" + id).text();
var tct = $("#TCity_" + id).text();
var ddt = $("#DDate_" + id).text();
var dt = $("#DTime_" + id).text();
var at = $("#ATime_" + id).text();
var cf = $("#CFare_" + fare).val();
$.ajax({
method: 'GET',
url: 'Flights/ReserveFlight',
data: { FromCity: fct, ToCity: tct, DepDate: ddt, DepTime: dt, ArrTime: at, CabinFare: cf },
success: function (data) {
console.log("data is inserted")
},
error: function (err) {
console.log(err)
}
});
}
when I click the save button it shows an error in the browser console and doesn't hit the debugger applied to the action method
here is my action method:
public ActionResult ReserveFlight(string FromCity, string ToCity, DateTime DepDate, DateTime DepTime, DateTime ArrTime, int CabinFare)
{
return View();
}
here is the error:
GET
http://localhost:64480/Flights/Flights/ReserveFlight?FromCity=Islamabd%20&ToCity=Karachi&DepDate=5%2F20%2F2022&DepTime=8%3A30%20AM&ArrTime=12%3A00%20AM&CabinFare=4500 404 (Not Found)
Modify the URL in ajax as:
$.ajax({
method: 'GET',
url: '/Flights/ReserveFlight',
data: { FromCity: fct, ToCity: tct, DepDate: ddt, DepTime: dt, ArrTime: at, CabinFare: cf },
success: function (data) {
console.log("data is inserted")
},
error: function (err) {
console.log(err)
}
});
Or work with UrlHelper.
$.ajax({
method: 'GET',
url: '#Url.Action("Flights", "ReserveFlight")',
data: { FromCity: fct, ToCity: tct, DepDate: ddt, DepTime: dt, ArrTime: at, CabinFare: cf },
success: function (data) {
console.log("data is inserted")
},
error: function (err) {
console.log(err)
}
});
Reference: Action(String, String) | UriHelper.Action() Method
Related
I have small projetc asp.net core mvc when i created view Razor with dropdownlist cascading i used Jquer Ajax to get the result of first dropdownlist by call the action of controller i have nothing on the second dropdownlist i test the action of the controller I Get JsonResult: result such as
[{"id_local":1,"metrage":150.0,"prix_vente":950000.0,"numAct":1,"activite":null,"type_local":"Commerce","num_Centre":1,"centre_Commercial":null},{"id_local":4,"metrage":190.0,"prix_vente":850000.0,"numAct":1,"activite":null,"type_local":"Commerce","num_Centre":1,"centre_Commercial":null}]
view Razor in below my code:
#{
ViewBag.Title =
"Vue Razor ";
}
<script src="~/lib/jquery/dist/jquery.js"></script>
<h2>Controle_WCS</h2>
<div class="row">
<div class="form-group">
#Html.DropDownList("ddlCentre", ViewBag.Centre_Commercial as List<SelectListItem>,
" -- Sélectionnez Centre Commercial --", new { #class = "form-control" })
<br />
#Html.DropDownList("ddlLocal", new List<SelectListItem>(),
" -- Sélectionnez Local --", new { #class = "form-control" })
</div>
</div>
#section scripts {
<script>
$(document).ready(function () {
$("#ddlCentre").change(function () {
//$("#ddlLocal").empty().append('<option>-- Sélectionnez Local --</option>');
var id = $(this).val();
alert('ID'+id);
if (id != "")
$.ajax({
url:"#Url.Action("GetLocalsList")",
type:"POST",
data:'Num_Centre='+id,
cache: false,
contentType: "application/json;charset=utf-8",
// data:"id_local="+id,
dataType:"json",
success:function (data) {
var json = $.parseJSON(data); // create an object with the key of the array
alert(json);
console.log(data);
$.each(data, function (index, row) {
$("#ddlLocal").append("<option value='" + row.id + "'>" + row.id + "</option>")
});
},
error: function (req, status, error) {
alert(error);
}
});
});
});
</script>
}
Action Controller :
[HttpGet]
public JsonResult GetLocalsList(int id)
{
List<Local> lstLocal= new List<Local>();
lstLocal = objLocal.GetLocalsData(id).ToList();
return Json(lstLocal);
}
Thanks in advance
Your GetLocalsList method is GET. So in the AJAX request, you have to change type to GET. The input parameter of GetLocalsList method is 'id', so you will have to change the data to 'id='+id. And when you are appending JSON result to ddlCentre, you are using row.id but your JsonResult seems to be id_local.
I made those changes to the AJAX request and tried a sample project. It is working for me.
$.ajax({
url:"#Url.Action("GetLocalsList")",
type:"GET",
data:'id='+id,
cache: false,
contentType: "application/json;charset=utf-8",
// data:"id_local="+id,
dataType:"json",
success:function (data) {
console.log(data);
$.each(data, function (index, row) {
$("#ddlLocal").append("<option value='" + row.id_local + "'>" + row.id_local + "</option>")
});
},
error: function (req, status, error) {
alert(error);
}
});
EDIT: The below code works, for anybody who would need!
This question is asked alot but couldn't find help for this specific one. I need to show a dropdown list that loads while I type in a search bar. While I type, I need to search in Active Directory for the Username that is being typed, and then it shows in the dropdown list all the options (say, it would only show results after 4 characters).
I have a simple form with one input, one button, a controller function to search user from a C# class that allows me to acces the AD. I put the JQuery script which retrieves data. The data is being correctly fetched but I cannot show it in the autocomplete. Any ideas?
The form:
<form class="form-inline" method="post" action="~/Home/SearchUserResult">
<label class="sr-only" for="inlineFormInput"> Nom et/ou Prénom </label>
<input type="text" class="form-control mb-2 mr-sm-2 mb-sm-0" name="searchName" id="searchName" placeholder="Nom et/ou prénom"/>
<button class="btn btn-primary" type="submit" id="searchValidate"> Rechercher </button>
</form>
My AD search function:
public List<string> SearchUserByName(string name)
{
try
{
SearchResultCollection resultCollection;
DirectoryEntry ldapConnection = createDirectoryEntry();
DirectorySearcher search = new DirectorySearcher(ldapConnection);
search.Filter = "(anr=" + name + ")";
search.PropertiesToLoad.Add("displayName");
resultCollection = search.FindAll();
if (resultCollection.Count == 0)
{
return null;
}
else
{
foreach(SearchResult sResult in resultCollection)
{
lastName.Add(sResult.Properties["displayName"][0].ToString());
}
}
return lastName;
}
catch (Exception e)
{
Console.WriteLine("Exception caught:\n\n" + e.ToString());
}
return null;
}
}
Here is the Controller function suggest by #caner
public ActionResult SearchUserByName(string name)
{
ADManager adManager = new ADManager();
List<string> lastName = adManager.SearchUserByName(name);
if (lastName != null)
{
ViewData["Names"] = lastName;
return Json(lastName,JsonRequestBehavior.AllowGet);
}
return null;
}
Finally here is the script I have for now, it gets the data but does not show it (in alert(data) I retrieve all the info I need):
<script>
$(function () {
$("#searchName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/SearchUserByName",
type: "GET",
data: { name: $("#searchName").val() },
contentType: "application/json;charset=utf-8",
dataType: "JSON",
success: function (data) {
alert(data)
response($.map(data, function (item) {
return {
label: item
}
}));
},
});
},
minLength: 4
})
});
</script>
Thanks for your help
EDIT: createDirectoryEntry() is a function I made just to create connection to AD.
EDIT 2 : If you have any other ideas to do that with something else than JQuery, I'm open to everything
Try jquery autocomplete like this...
your script:
$(function () {
$("#searchName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/YourController/SearchUserByName",
type: "POST",
data: { name: $("#searchName").val() },
dataType: "JSON",
success: function (data) {
response($.map(data.lastName, function (item) {
return {
label: item
}
}));
},
});
},
minLength: 4
})
});
and your controller method:
public ActionResult SearchUserByName(string name)
{
.
.
.
return Json(lastName);
}
This script works for me:
<script>
$(function () {
$("#searchName").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Home/SearchUserByName",
type: "GET",
data: { name: $("#searchName").val() },
contentType: "application/json;charset=utf-8",
dataType: "JSON",
success: function (data) {
alert(data)
response($.map(data, function (item) {
return {
label: item
}
}));
},
});
},
minLength: 4
})
});
</script>
I'm having some issues with updating a partial view in my index view. Basically, based on a click, I would like to have updated information.
//controller
public ActionResult Index()
{
var filteredObservations = getFilteredObservationSessions().ToList();
var observationManagementVm = new ObservationManagementVM(filteredObservations);
return View(observationManagementVm);
}
public ActionResult indexPagedSummaries(int? page, List<ObservationSessionModel> data)
{
var alreadyFilteredObservations = data;
int PageSize = 10;
int PageNumber = (page ?? 1);
return PartialView(alreadyFilteredObservations.ToPagedList(PageNumber, PageSize));
}
My main view
//index.cshtml
#model AF.Web.ViewModels.ObservationManagementVM
....
<div id="testsim">
#Html.Action("indexPagedSummaries", new { data = Model.ObservationSessions })
</div>
<input id="new-view" value="Sessions" type="button" />
<script>
$("#new-view").click(function() {
$.ajax({
type: "GET",
data: { data: "#Model.FeedBackSessions" },
url: '#Url.Action("indexPagedSummaries")',
cache: false,
async: true,
success: function (result) {
console.log(result);
$('#testsim').html(result);
$('#testsim').show();
}
});
});
</script>
....
And my partial view
//indexPagedSummaries.cshtml
#model PagedList.IPagedList<AF.Services.Observations.ObservationSessionModel>
#using (Html.BeginForm("indexPagedSummaries"))
{
<ol class="vList vList_md js-filterItems">
#foreach (var item in Model)
{
#Html.DisplayFor(modelItem => item)
}
</ol>
<div>
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index",
new { page }))
</div>
}
Html.Action() returns what I want perfectly, but it doesn't seem to be able to be triggered by a button click.
So, I'm not getting any errors, but the url doesn't give any data back. When I try to run the Observation/indexPagedSummary url without passing in data, I get a System.ArgumentNullException error, so I'm assuming that something is being transferred to the view model. Any help would be so appreciated.
Have not run your code but I believe it is because you are not sending the data along with the #Url.Action
Main View:
//index.cshtml
#model AF.Web.ViewModels.ObservationManagementVM
....
<div id="testsim">
#Html.Action("indexPagedSummaries", new { data = Model.ObservationSessions })
</div>
<input id="new-view" value="Sessions" type="button" />
<script>
$("#new-view").click(function() {
$.ajax({
type: "GET",
data: { data: "#Model.FeedBackSessions" },
url: '#Url.Action("indexPagedSummaries", "[Controller Name]", new { data = Model.ObservationSessions})',
cache: false,
async: true,
success: function (result) {
console.log(result);
$('#testsim').html(result);
$('#testsim').show();
}
});
});
</script>
If that doesn't help I have had issues when I have had a content-type mismatch or a datatype mismatch. You may need to add those to you ajax request.
Change your ajax data line to this:
data: { data: JSON.stringify(#Model.FeedBackSessions) },
You may also need to add these lines to the ajax:
dataType: 'json',
contentType: 'application/json; charset=utf-8',
You can see in one of your comments above that the current URL is being formed with a description of the List Object, rather than the contents of it:
http://localhost:60985/Observation/indexPagedSummaries?data=System.Collections.Generic.List%601%5BAF.Services.Observations.ObservationSessionModel%5D&data=System.Collections.Generic.List%601%5BAF.Services.Observations.ObservationSessionModel%5D&_=1482453264080
I'm not sure if there's a better way, but you may even have to manually get the model data into Javascript before posting it.
eg:
<script>
var temp = [];
#foreach (var item in Model.FeedBackSessions){
#:temp.push(#item);
}
</script>
and then data: { data: JSON.stringify(temp) },
I want to change the drop down list(ddlSite) when user change the another drop down list(ddlCompany).
So I don't know how to add the new items to ddlsite drop down list.
Ajax Function
function getSite(companyID) {
alert(companyID);
$.ajax({
type: 'POST',
dataType: 'html',
url: '#Url.Action("SiteList", "Site")',
data: ({ ComID: companyID }),
success: function (result) {
alert(result);
$('#SiteList').html(result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
}
My view
#Html.DropDownList("ddlCompany", ViewData["AllCompany"] as SelectList, "--Select Item--", new { #onchange = "getSite(this.value);" })
<div id="SiteList">
#Html.Partial("_siteList", SiteList)
</div>
This is my controller
public ActionResult SiteList(int ComID)
{
var siteQuery = from s in db.tblSites
orderby s.SiteName
where s.FKComId == ComID
select s;
IEnumerable<SelectListItem> AllSite = new SelectList(siteQuery, "PKSiteID", "SiteName");
ViewBag.AllSite = siteQuery;
return PartialView("_siteList", siteQuery);
}
My partial view
#model SKG_website.Models.tblSite
#{
ViewBag.Title = "_siteList";
var allSites = ViewBag.AllSite as IEnumerable<SKG_website.Models.tblSite>;
}
<div id="siteList" class="editor-field">
#Html.DropDownListFor(model => model.PKSiteID, new SelectList(allSites, "PKSiteID", "SiteName"))
</div>
I don't know how to assign the sslsit drop down list in the AJAX function. How do I do it?
I'm looking for a way to do a "Update Panel" in ASP.NET MVC 3. I found this link: How to make update panel in ASP.NET MVC but didn't work.
So, i did this in my view:
<div>
<input type="text" id="userName" />
<button type="button" onclick="searchUserByName()">Search</button>
</div>
<div id="usersPanel">
#{Html.RenderPartial("_UserList", Model);}
</div>
<script type="text/javascript">
function searchUserByName() {
var userName = $("#userName").val();
$.post('#Url.Action("SearchUserByName")',
{username: userName},
function (htmlPartialView) {
$("#usersPanel").html(htmlPartialView);
}
);
}
</script>
And in my controller:
public ActionResult SearchUserByName(string userName)
{
List<User> users = // code to search users by name
return PartialView("_UserList", users);
}
But i don't know if is a good (or right) way to do that, or if there is a way to do this with asp.net mvc 3. There is a better way to do this, or with asp.net mvc 3?
Just use ajax request to get the results from your action methods. It basically does the same thing as update panels in asp.net.
So something like the following.
$.ajax({
async: false,
cache: false,
type: 'POST',
url: /controller/action,
data: { id: idParam },
beforeSend: function (XMLHttpRequest) {
if (confirmMessage !== undefined) {
return confirm(confirmMessage);
}
return true;
},
success: function (data) {
// do stuff
},
error: function () {
alert('An error occured');
}
});
I would do it like that.
You might also want to take a look at client side libraries for handling bindings etc. Looks like knockoutjs will be included in MVC4
In View:
<script type="text/javascript">
var userName = $("#userName").val();
$.ajax({
url: "/<ControolerName>/SearchUserByName",
type: "POST",
data: { userName: userName},
success: function (result) {
$('#divResults').html(result);
},
error: function (ex) {
alert("Error");
}
<script>
<div id="divResults">
</div>
In controller:
public PartialViewResult SearchUserByName(string userName)
{
List<User> users = // code to search users by name
return PartialView("_users", users);
}