I am trying to filter datatable by select.
I can see the data in select but don't know how to filter it.
Here's my code.
Thanks
function getSearchList() {
$.post('#(Url.Action("GetSearchList", "ESR"))')
.success(function (data) {
if (data.length > 0) {
$.each(data, function () {
$('#Search_Id').append($('<option>', {
value: this.ID,
text: this.S_ID
}));
});
}
$(window).unblock();
})
}
and
$(document).ready(function () {
$('#Search_Id').select2({
placeholder: "Search",
allowClear: true,
});
});
and
<div class="col-sm-2">
<select class="select" id="Search_Id"></select>
</div>
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
following are whole backend side of codes
public List<SearchId> GetSearchIdData()
{
string strSQL = string.Format(#"SELECT ID, S_ID FROM TBR");
using (var conn = SqlUtility.GetDBConnection())
{
conn.Open();
return conn.Query<SearchId>(strSQL).ToList();
}
}
and
public ActionResult GetSearchIdList()
{
JsonResult result;
List<SearchId> List = service.GetSearchIdList();
result = Json(List);
result.MaxJsonLength = int.MaxValue;
return result;
}
and
public class SearchId
{
public int ID { get; set; }
public string S_ID{ get; set; }
}
and
public List<SearchId> GetSearchIdList()
{
return repo.GetSearchIdData();
}
Related
I'm trying to load a partial view and change it through a POST Ajax, but model doesn't update on view.
This is how I'm loading my partial:
#{
Html.RenderAction("UltimeNovità", "User");
}
and my action in UserController is:
public ActionResult UltimeNovità()
{
_UltimeNovitàViewModel model = new _UltimeNovitàViewModel();
model.NumeroPagina = 1;
return PartialView("~/Views/User/Partial/_UltimeNovità.cshtml",model);
}
and here the partial:
#model Mine.Models._UltimeNovitàViewModel
<script>
$(document).ready(function () {
});
function nextPage() {
$.ajax({
url: '#Url.Action("UltimeNovitàPaginaSuccessiva")',
type: 'POST',
data: { pagina: #Model.NumeroPagina },
success: function (data) {
$('#x').text('#Model.NumeroPagina');
},
error: function (xhr) {
alert('error');
}
});
}
</script>
<p id="x">1</p>
finally, the POST action in the same controller:
[HttpPost]
public ActionResult UltimeNovitàPaginaSuccessiva(int pagina)
{
_UltimeNovitàViewModel model = new _UltimeNovitàViewModel();
ModelState.Clear();
model.NumeroPagina = pagina + 1;
model.UltimeNovità = UserControllerMethods.GetUltimeNovità(model.NumeroPagina);
return PartialView("~/Views/User/Partial/_UltimeNovità.cshtml", model);
}
My problem is: why after the POST action #Model.NumeroPagina is always 1? I expect that each time I press the button which calls the function with ajax the #Model.NumeroPagina increases by 1 and it's shown in my paragraph.
The button is in the main page that contains the partial, actions are always hit and during debugging I can see that model.NumeroPagina is 2, but in view is always 1.
There are some issues in your code. I don't see where you're updating the HTML content, also you're generating the nextPage function eachTime, and others.
Check this sample, it should be easy to use.
Controller/ViewModel
public class NovitàController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult UltimeNovità(int? page)
{
var model = new UltimeNovitàViewModel
{
NumeroPagina = 1
};
return PartialView("_UltimeNovità", model);
}
[HttpPost]
public ActionResult UltimeNovitàPaginaSuccessiva(int pagina)
{
var model = new UltimeNovitàViewModel
{
NumeroPagina = pagina + 1,
UltimeNovità = GetUltimeNovità(pagina + 1)
};
return PartialView("_UltimeNovità", model);
}
public string GetUltimeNovità(int page)
{
return $"Ultime Novità: {page}"; //FOR DEMO
}
public class UltimeNovitàViewModel
{
public int NumeroPagina { get; set; }
public string UltimeNovità { get; set; }
}
}
_UltimeNovità partial view:
#model NovitàController.UltimeNovitàViewModel
#if (Model.UltimeNovità != null)
{
<div>
UltimeNovità: #Model.UltimeNovità
</div>
}
<div>
Pagina: #Model.NumeroPagina
</div>
<div>
<a class="next-page-link" href="#Url.Action("UltimeNovitàPaginaSuccessiva", "Novità", new {pagina = Model.NumeroPagina})">
Pagina Successiva
</a>
</div>
And the Index page:
#{
ViewBag.Title = "Novità";
}
<div id="RootDiv">
#{ Html.RenderAction("UltimeNovità", "Novità");}
</div>
#section scripts{
<script>
$(function() {
function bindNextPageLink() {
$("#RootDiv a.next-page-link").click(function(event) {
event.preventDefault();
$.post($(this).attr("href"),
function(data) {
$("#RootDiv").html(data);
bindNextPageLink();
}
);
});
}
bindNextPageLink();
});
</script>
}
I tried to write the example very similar to your code.
Banging my head against a brick wall here. I have a Datatable that is populated by GET call to an api from a dropdown box. Ideally i want the user to select an option in the dropdown and the table will reload with the data from the call.
The api is getting called and data is being returned with each selection but the table doesnt display the data or get refreshed like i would expect.
CheckIn.cshtml
#model IEnumerable<Vidly.Models.Customer>
#{
ViewBag.Title = "CheckIn";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>CheckIn</h2>
<div class="form-group">
#Html.DropDownList("Customers",
new SelectList(Model, "Id", "Name"), "Please select a customer",
new { #class = "form-control", #id = "customers"})
</div>
<table id="rentals" class="table table-bordered table-hover">
<thead>
<tr>
<th>Id</th>
</tr>
</thead>
<tbody></tbody>
</table>
#section scripts
{
<script>
$(document).ready(function () {
var customerId;
var table = $("#rentals").DataTable({
ajax: {
type: 'GET',
url: '/api/RentalsApi/',
data: function (d) {
d.id = customerId ? customerId : -1;
},
dataSrc: ""
},
columns: [
{
data: "name"
}
]
});
$('#customers').on('change', function (e) {
console.log(this.value);
customerId = this.value;
table.ajax.reload();
});
});
</script>
}
API
// GET /api/RentalsApi/{1}
[HttpGet]
public IHttpActionResult GetRental(int id)
{
if (id == -1) return Json(new System.Web.Mvc.EmptyResult());
var customer = _context.Customers.SingleOrDefault(c => c.Id == id);
return Ok(customer);
}
Customer Model
using System;
using System.ComponentModel.DataAnnotations;
namespace Vidly.Models
{
public class Customer
{
public int Id { get; set; }
[Required(ErrorMessage = "Please enter customer's name.")]
[StringLength(255)]
public string Name { get; set; }
public bool IsSubscribedToNewsletter { get; set; }
public MembershipType MembershipType { get; set; }
[Display(Name = "Membership Type")]
public byte MembershipTypeId { get; set; }
[Display(Name = "Date of Birth")]
[Min18YearsIfAMember]
public DateTime? Birthdate { get; set; }
}
}
Just make your ajax api call as normal and then use this to redraw the table
table=$("#rentals").DataTable()
table.clear().rows.add(newData).draw(); //newData is the data you get from your ajax call
I am new to both asp.net MVC and JQuery so be gentle.
I am trying to use a HTTP Post to update my contact form, used to send an email, using AJAX. I have seen lots of posts but what I want seems specific and I cant seem to find anything relevant.
The down low: I have a layout page which has the header, renders the body and has my footer in. My footer contains the form I want to submit. I want to submit this form without refreshing the whole page. The layout page:
<div id="footer">
#{Html.RenderAction("Footer", "Basic");}
</div>
<p id="p"></p>
I have a model for this form to send an email.
namespace SimpleMemberShip.Models
{
public class EmailModel
{
[Required, Display(Name = "Your name")]
public string FromName { get; set; }
[Required, Display(Name = "Your email"), EmailAddress]
[StringLength(100, ErrorMessage = "The email address entered is not valid")]
public string FromEmail { get; set; }
[Required]
public string Message { get; set; }
}
The footer:
<h2> footer yo !</h2>
#Html.ValidationSummary()
<fieldset>
<legend>Contact Me!</legend>
<ol>
<li>
#Html.LabelFor(m => m.FromEmail)
#Html.TextBoxFor(m => m.FromEmail)
</li>
<li>
#Html.LabelFor(m => m.FromName)
#Html.TextBoxFor(m => m.FromName)
</li>
<li>
#Html.LabelFor(m => m.Message)
#Html.TextBoxFor(m => m.Message)
</li>
</ol>
<button id="submit"> Submit </button>
</fieldset>
controller:
[ChildActionOnly]
public ActionResult Footer()
{
return PartialView("~/Views/Shared/_Footer.cshtml");
}
[HttpPost]
public ActionResult Footer(EmailModel model)
{
return PartialView("~/Views/Shared/_Footer.cshtml");
}
I want to use the model validation and everything to be the same or similar as if the form was posted normally through the server.
Edit:
My new code, which works great! but it only works once, when the button is clicked again nothing happens. Anyone know why?
<script type="text/javascript">
$("#submit").click(function () {
$("#footer").html();
var url = '#Url.Action("Footer", "Basic")';
$.post(url, { FromName: $("[name=FromName]").val(), FromEmail: $(" [name=FromEmail]").val(), Message: $("[name=Message]").val() }, function (data) {
$("#footer").html(data);
});
var name = $("[name=FromName]").val();
$("#p").text(name);
});
</script>
new Edit:
did some research and using
$("#submit").live("click",function () {
instead of
$("#submit").click(function () {
seemed to do the trick.
<script type="text/javascript">
$("#submit").live("click",function () {
$('.validation-summary-errors').remove();
var url = '#Url.Action("Footer", "Basic")';
$.post(url, { FromName: $("[name=FromName]").val(), FromEmail: $("[name=FromEmail]").val(), Message: $("[name=Message]").val() }, function (data) {
$("#footer").html(data);
});
});
</script>
ended up with this but will try the "serialize()" option next time.
controller was changed to this without the [ChildActionOnly] and works perfect now
[HttpPost]
public ActionResult Footer(EmailModel model)
{
return PartialView("~/Views/Shared/_Footer.cshtml");
}
Thank you everyone that helped!
Change the [ChildActionOnly] to [HttpGet] in the controller
You can pass model data to controller by doing the following steps
1. Get the input values on click of submit and sent to the Footer action in controller
$("#submit").click(function () {
var FromEmailValue = $('#FromEmail').val();
var FromNameValue = $('#FromName').val();
var MessageValue = $('#Message').val();
var url = '#Url.Action("Footer", "Basic")';
$.ajax({
url: urlmodel,
data: { FromName: FromNameValue, FromEmail: FromEmailValue, Message: MessageValue},
cache: false,
type: "POST",
success: function (data) {
do something here
}
error: function (reponse) {
do something here
}
});
});
In the controller
``
[HttpGet]
public ActionResult Footer()
{
return PartialView("~/Views/Shared/_Footer.cshtml");
}
[HttpPost]
public ActionResult Footer(string FromName = "", string FromEmail = "", string Message = "")
{
//for ajax request
if (Request.IsAjaxRequest())
{
do your stuff
}
}
NPG_Chemical_Measurement_Methods is an ICollection type. In my Chemical.cshtml, I have:
<div id="nioshs">
#Html.EditorFor(model => model.NPG_Chemical_Measurement_Methods)
</div>
and in the EditorTemplate view:
<div class="method" style="display:inline-block;">
<p>
#Html.RemoveLink("x", "div.method", "input.mark-for-delete")
#Html.HiddenFor(x => x.DeleteMethod, new { #class = "mark-for-delete" })
#Html.TextBoxFor(x => x.Measurement_Method)
#Html.ValidationMessageFor(model => model.Measurement_Method, "", new { #class = "text-danger" })
#Html.Hidden("Measurement_Type", "NIOSH")
</p>
</div>
I want to have something like when I give input for #Html.TextBoxFor(x => x.Measurement_Method), then click on other place of the current page, an alert will popup says Not exist in Database if record cannot be found in Measurement_Method table.
NPG_Chemical.cs has:
public partial class NPG_Chemical
{
public NPG_Chemical()
{
this.NPG_Chemical_Measurement_Methods = new HashSet<NPG_Chemical_Measurement_Method>();
}
[StringLength(256)]
[Remote("IsUserExists", "NPG_Chemical", ErrorMessage = "Chemical Name already in use")]
public string Chemical { get; set; }
public virtual ICollection<NPG_Chemical_Measurement_Method> NPG_Chemical_Measurement_Methods { get; set; }
internal void CreateMeasurementMethods(int count = 1)
{
for (int i = 0; i < count; i++)
{
NPG_Chemical_Measurement_Methods.Add(new NPG_Chemical_Measurement_Method());
}
}
Measurement_Method.cs has:
public partial class NPG_Chemical_Measurement_Method
{
[StringLength(256)]
[Remote("IsNIOSHExists", "NPG_Chemical", ErrorMessage = "NIOSH number does not exist")]
public string Measurement_Method { get; set; }
}
NPG_ChemicalController has:
public JsonResult IsUserExists(string Chemical)
{
return Json(!db.NPG_Chemical.Any(x => x.Chemical == Chemical), JsonRequestBehavior.AllowGet);
}
public JsonResult IsNIOSHExists(string Measurement_Method)
{
System.Diagnostics.Debug.WriteLine("value:",Measurement_Method);
return Json(db.NPG_NIOSH_Method.Any(x => x.Measurement_Number == Measurement_Method), JsonRequestBehavior.AllowGet);
}
This hopefully will get you close. I'm just writing this from memory. But basically one way to do this is handle an onblur event of your textbox with a javascript function. Then do an ajax call to a controller sending the value of Measurement_Method, validate the data and return true or false. If false show an alert box. You'll need to include the jquery library to use this.
#Html.TextBoxFor(x => x.Measurement_Method, new {onblur = "Validate()"})
Then javascript
function Validate() {
$.ajax({
url: "#Url.Action("CheckTextField", "Controller")\?value=" + $('#Measurement_Method').val(),
dataType: "html",
success: function(data) {
if (data == "false")
{
alert('Not exist in Database');
}); }
Your controller
public string CheckTextField(string value)
{
//validate the value here
return "true" or "false"
}
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Why JavaScript is not working on this project? Can anyone tell me the reason why this is happening? I also comment the script links on my _Layout but still doesn't work.
The Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace FA_CS.Models.Credit
{
public class CreditCarModel
{
public string SelectedProvinceId { get; set; }
public string SelectedCityId { get; set; }
public string SelectedSuburbId { get; set; }
public IEnumerable<Province> Provinceses { get; set; }
}
public class Province
{
public string Id {get;set;}
public string Name {get;set;}
}
}
Here is the View
This is the view of my project and the internal and external JS in this project.
#model FA_CS.Models.Credit.CreditCarModel
#{
ViewBag.Title = "Spider";
}
<script type="text/javascript" src="/scripts/jquery-1.4.4.js"></script>
<script type="text/javascript">
$(function () {
$('#SelectedProvinceId').change(function () {
var selectedProvinceId = $(this).val();
$.getJSON('#Url.Action("Cities")', { provinceId: selectedProvinceId }, function (cities) {
var citiesSelect = $('#SelectedCityId');
citiesSelect.empty();
$.each(cities, function (index, city) {
citiesSelect.append(
$('<option/>')
.attr('value', city.Id)
.text(city.Name)
);
});
});
});
$('#SelectedCityId').change(function () {
var selectedCityId = $(this).val();
$.getJSON('#Url.Action("Suburbs")', { cityId: selectedCityId }, function (suburbs) {
var suburbsSelect = $('#SelectedSuburbId');
suburbsSelect.empty();
$.each(suburbs, function (index, suburb) {
suburbsSelect.append(
$('<option/>')
.attr('value', suburb.Id)
.text(suburb.Name)
);
});
});
});
});
</script>
<div>
Province:
#Html.DropDownListFor(x => x.SelectedProvinceId, new SelectList(Model.Provinceses, "Id", "Name"))
</div>
<div>
City:
#Html.DropDownListFor(x => x.SelectedCityId, Enumerable.Empty<SelectListItem>())
</div>
<div>
Suburb:
#Html.DropDownListFor(x => x.SelectedSuburbId, Enumerable.Empty<SelectListItem>())
</div>
Controller
This is the controller of my project
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FA_CS.Models.Credit;
namespace FA_CS.Controllers
{
public class HomeController : Controller
{
public ActionResult Spider()
{
var model = new CreditCarModel
{
Provinceses = Enumerable.Range(1, 10).Select(x => new Province
{
Id = (x + 1).ToString(),
Name = "Province" + x
})
};
return View(model);
}
public ActionResult Suburbs(int cityId)
{
var suburbs = Enumerable.Range(1, 5).Select(x => new
{
Id = x,
Name = "suburb" + x
});
return Json(suburbs, JsonRequestBehavior.AllowGet);
}
public ActionResult Cities(int provinceId)
{
var cities = Enumerable.Range(1, 5).Select(x => new
{
Id = x,
Name = "city" + x
});
return Json(cities, JsonRequestBehavior.AllowGet);
}
}
}
You need to call the ajax by $.ajax().
You wrote :
$.getJSON('#Url.Action("Cities")', { provinceId: selectedProvinceId }, function (cities) {
var citiesSelect = $('#SelectedCityId');
citiesSelect.empty();
$.each(cities, function (index, city) {
citiesSelect.append(
$('')
.attr('value', city.Id)
.text(city.Name)
);
});
});
Instead of that you need to code :
var citiesSelect = $('#SelectedCityId');
$.ajax({
url: "/Home/Cities",
type: "GET", //these is must
async: false, //these is optional
cache: false, //these is for IE
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { provinceId: 1 },
success: function (data) {
$('#SelectedSuburbId').html("");
var cities=eval(data);
var citiesHtml = "";
for (i = 0; i < cities.length; i++) {
citiesHtml += '<option value="' + cities[i].Id + '" >' + cities[i].Name + '</option>';
}
$('#SelectedSuburbId').html(citiesHtml);
}
});
You get the return of the json call by "data"
With the above code drop down can be populated.
But for getting the values you need to run a query in top of the “Cities” method.
And return a list of city.
public ActionResult Cities(int provinceId)
{
var cities = Enumerable.Range(1, 5).Select(x => new
{
Id = x,
Name = "city" + x
});
return Json(cities, JsonRequestBehavior.AllowGet);
}
}