I am newbie to asp.net MVC4.
For searching names from list i tried a search filter in MVC4.
This is controller-
public ActionResult SearchUser(string Email, int? UserId) {
var system = from u in db.SystemUsers
select u;
if (!String.IsNullOrEmpty(Email)) {
system = system.Where(c => c.Email.Contains(Email));
}
return View(system.Where(x=>x.Email==Email));
}
View-
<input type="text" id="search-User" />
<button id="text-email">search</button>
Ajax handling-
<script type="text/javascript">
$(document).ready(function () {
$('#text-email').click(function () {
var areavalue = $('#search-User').val();
alert(areavalue);
$.ajax({
url: '/Allusers/SearchUser/?Email=' + areavalue,
type: 'get',
datatype: 'json'
});
});
});
</script>
ViewModel-
public class UserModel
{
[Required]
public string Email { get; set; }
public int UserId { get; set; }
}
I have many users as a list, so i wanted to filter out any user from the list. For this I am using input element to get exact name as it is in list. Thus this name is passed to controller to find the exact match.
It is showing value i passed through ajax handling but not showing filtered result.
How can I perform searching in Asp.net MVC4?
I would use better Load() function for this porpose:
<script>
$(function () {
$('#text-email').click(function () {
var areavalue = $('#search-User').val();
$(".YourDivForResults").Load('/Allusers/SearchUser/?Email=' + areavalue)
});
});
</script>
And, as a recommendation, modify a bit your ActionResult as follows:
system = system.Where(c => c.Email.ToUpper().Trim().Contains(Email.ToUpper().Trim()));
This way you will avoid problems with empty spaces and Upper or Low letters.
Your ajax function is sending the data up to the server, but it is not doing anything with the result. In order to use the results, you should use the done promise method in the jQuery .ajax method that you are calling. It will look something like this:
$.ajax({
url: '/Allusers/SearchUser/?Email=' + areavalue,
type: 'get',
datatype: 'json'
}).done(
function(data, textStatus, jqXHR) {
var object = jQuery.parseJSON(data);
// LOGIC FOR UPDATING UI WITH RESULTS GOES HERE
}
);
You could alternatively use the Success callback option (instead of done). But the key is to provide logic for what to do with the data returned by the Action.
Also, if you are intending to return results using your ViewModel, you may need to return UserModel objects from your Linq query.
And if you are expecting JSON back from your action, you should not return View. Instead, try returnins JSON(data). (See here for more).
You need to make small change to you action like,
public ActionResult SearchUser(string Email, int? UserId) {
var system = from u in db.SystemUsers
select u;
if (!String.IsNullOrEmpty(Email)) {
system = system.Where(c => c.Email.Contains(Email));
}
return Json(system.Where(x=>x.Email==Email),JsonRequestBehavior.AllowGet);
}
and in your ajax call
$(document).ready(function () {
$('#text-email').click(function () {
var areavalue = $('#search-User').val();
alert(areavalue);
$.ajax({
url: '/Allusers/SearchUser/?Email=' + areavalue,
type: 'get',
datatype: 'json',
success:function(data){JSON.stringify(data);}
});
});
});
so that you will get the search result in a json format. you can make use of it. Hope it helps
Related
In my view, I have an AJAX call which sends an id parameter to my controller. This bit works fine. In my controller, I plan to query the database with that id, pull out associated data and want to send this back to the AJAX call/view. This is the bit I am struggling with, as I am new to AJAX calls.
var chosenSchoolID = $("#SelectedSchoolId").val();
$.ajax({
url: "/Home/GetSchoolDetailsAJAX",
type: "POST",
data: {
schoolID: chosenSchoolID
},
dataType: "text",
success: function(data) {
if (data == "success") {
}
},
error: function(data) {
if (data == "failed")
alert("An error has occured!");
}
});
The above is my AJAX call, and this does hit my controller method. However in my controller, I want to now send back other string data and I am unsure on how to do this (just placeholder code currently)
[HttpPost]
public ActionResult GetSchoolDetailsAjax(string schoolID)
{
// query database using schoolID
// now we have other data such as:
string SchoolName = "";
string SchoolAddress = "";
string SchoolCity = "";
return null;
}
Must I declare variables in my Jquery and pass into the data parameter of the AJAX call in order for the values to be passed?
Many thanks in advance
The simplest way to do this is to return the entities retrieved from your database using return Json() from your controller.
Note that when retrieving data then a GET request should be made, not a POST. In addition the default MVC configuration should have the routes setup to allow you to provide the id of the required resource in the URL. As such, try this:
$.ajax({
url: "/Home/GetSchoolDetailsAJAX/" + $("#SelectedSchoolId").val(),
type: "get",
success: function(school) {
console.log(school);
},
error: function() {
alert("An error has occured!");
}
});
[HttpGet]
public ActionResult GetSchoolDetailsAjax(string id) {
var school = _yourDatabaseContext.Schools.Single(s => s.Id == id); // assuming EF
return Json(school);
}
If you'd like to test this without the database integration, amend the following line:
var school = new {
Id = id,
Name = "Hogwarts",
Address = "Street, City, Country"
};
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
I'm refactoring my ASP .net core project and I want to make use of some Ajax calls, but I'm facing the following problem: when I try to send a request to a method in a controller of my project but it doesn't work.
I have a modal with the following button:
<button onclick="reviewRestaurant(#item.RestaurantId)" class="btn btn-outline-primary">Add review</button>
the reviewRestaurant() function looks like this:
function reviewRestaurant(restaurantId) {
let rating = $("input[type=radio]:checked").val();
let review = $('textarea').val();
let data = { restaurantId, rating, review };
$.ajax({
type: "POST",
url: `/Restaurants/Review`,
data: JSON.stringify(data),
success: function (res) {
// TODO: work on this later
},
error: function (err) {
console.log(err);
}
});
}
And the method that I wanna call in the Restaurants controller looks like so:
[Authorize]
[HttpPost]
public async Task<IActionResult> Review(int restaurantId, string rating, string content)
{
var username = this.User.Identity.Name;
await this.restaurantsService.Review(restaurantId, username, rating, content);
return this.RedirectToAction("Details", new { id=restaurantID });
// the output of this method will be refactored later once I manage to get to it
}
The problem is I cannot reach the Review method in the controller. I get the 400 status code and I don't know how to fix it. I tried using DTO and [FormData] attribute for the method parameters and tried passing the data without stringifying it still nothing works.
If anyone can help me I would be very grateful. I'm relatively new to ajax calls and simply cannot see where my mistake is.
You can try this solution:
Create a common class for your parameters (int restaurantId, string rating, string content) and use FromBody. => Review([FromBody] YourClassName)
And write this parameters in your ajax code.
contentType: 'application/json; charset=utf-8',
data: 'json'
I hope it will help you.
Here is a working demo which I test.
#section Scripts
{
<script>
function reviewRestaurant(restaurantId) {
let rating = $("input[type=radio]:checked").val();
let content = $('textarea').val();
let data = { restaurantId, rating, content };
$.ajax({
type: "POST",
url:'/Restaurants/Review',
data: data,
success: function (res) {
// TODO: work on this later
},
error: function (err) {
console.log(err);
}
});
}
</script>
}
I reallly have a simple set of code to bring back a set of data that is triggered off a drop down.
this is the script:
function () {
$('#ProviderID').change(function () {
$.ajax({
url: '/servicesDisplay/Index',
type: 'Get',
data: { id: $(this).attr('value') },
success: function (result) {
// The AJAX request succeeded and the result variable
// will contain the partial HTML returned by the action
// we inject it into the div:
$('#serLocations').html(result);
}
});
});
This is the controller:
public ActionResult Index(string id)
{
int prid = Int32.Parse(id.Substring(0, (id.Length-1)));
string mulitval = id.Substring((id.Length-1), 1).ToString();
System.Data.Objects.ObjectResult<getProviderServiceAddress_Result> proList = theEntities.getProviderServiceAddress(prid);
List<getProviderServiceAddress_Result> objList = proList.ToList();
SelectList providerList = new SelectList(objList, "AddressID","Address1");
//ViewBag.providerList = providerList;
return PartialView("servicesDisplay/Index", providerList);
}
This is the view:
#model OCS_CS.Models.servicesDisplay
<div>
#Html.DropDownList(model => model.ServiceAdderssID, (IEnumerable<SelectListItem>)model)
</div>
When the drop down passes the in the value. The apps does hit the controller. But it highlightes the drop down in a light red and the view never displays.
Try this short version which uses the jquery load method.
$(function(){
$('#ProviderID').change(function () {
$('#serLocations').load("#Url.Action("Index","ServicesDisplay")?id="
+$(this).val());
});
});
If you want to avoid caching of result, you may send a unique timestamp along with the querystring to avoid caching.
$('#serLocations').load("#Url.Action("Index","ServicesDisplay")?id="
+$(this).val()+"&t="+$.now());
You are doing a GET, thats no meaning to pass data to ajax, you may pass data for POST:
First, put the value at the URL:
function () {
$('#ProviderID').change(function () {
$.ajax({
url: '/servicesDisplay/Index/' + $(this).attr('value'),
type: 'Get',
success: function (result) {
// The AJAX request succeeded and the result variable
// will contain the partial HTML returned by the action
// we inject it into the div:
$('#serLocations').html(result);
}
});
});
Second, mark the method as GET
[HttpGet]
public ActionResult Index(string id)
Hopes this help you!
You have quite a few problems with your code. First the model defined for your view is:
#model OCS_CS.Models.servicesDisplay
but in your action your're invoking the call to this view by passing in a SelectList:
SelectList providerList = new SelectList(objList, "AddressID","Address1");
return PartialView("servicesDisplay/Index", providerList);
this is not going to fly because the models do not match by type. Seconds problem is you are casting this SelectList into an IEnumerable. This is also not going to work. You need to cast to SelectList:
#Html.DropDownList(model => model.ServiceAdderssID, (SelectList)model)
but again until you match the type of your model in your action with the model on your view none of this will work. I suggest you install Fiddler to help you determine what sort of error are you getting.
I've never used ajax and I'm just try to see if this will call the method from my controller and give me the desired result. The javascript debugger in VS doesn't seem to be working at the moment. Does this look right?
$("form").submit(function() {
var hasCurrentJob = $.ajax({
url: 'Application/HasJobInProgess/#Model.ClientId'
});
});
controller method
public Boolean HasJobInProgress(int clientId)
{
return _proxy.GetJobInProgress(clientId).Equals(0);
}
Update
$("#saveButton").click(function() {
var hasCurrentJob = false;
$.ajax({
url: '#Url.Action("HasJobInProgress","ClientChoices")/',
data: { id: #Model.ClientId },
success: function(data){
hasCurrentJob = data;
}
});
if (hasCurrentJob) {
alert("The current clients has a job in progress. No changes can be saved until current job completes");
}
});
Try to use the Url.Action HTML Helper method when calling an action method. This will get you the correct url to the action method. You dont need to worry about how many ../ to add/
$(function(){
$("form").submit(function() {
$.ajax({
url: '#Url.Action("HasJobInProgess","Application")',
data: {clientId: '#Model.ClientId'},
success: function(data) {
//you have your result from action method here in data variable. do whatever you want with that.
alert(data);
}
});
});
});