View
<script type="text/javascript">
$(document).ready(function () {
$("#getRates").click(function () {
$.ajax(
{
type: "POST",
url: '#Url.Action("GetDetail", "ControllerName")',
data: {}
}).success(function () {
alert("hit!")
$('#MyTable').load(location.href + " #MyTable")
});
});
});
</script>
<button type="button" id="getRates" class="button getRates">Get Rates</button>
<br /><br /><br />
<table id="MyTable">
<tr>
<th width="15%">Name</th>
<th width="15%">Address</th>
<th width="15%">City</th>
<th width="15%">State</th>
</tr>
<tr>
<td>#GetRateModel.OriginName</td>
<td>#GetRateModel.OriginAddress</td>
<td>#GetRateModel.OriginCity</td>
<td>#GetRateModel.OriginState miles</td>
</tr>
<tr>
<td>#GetRateModel.DestName</td>
<td>#GetRateModel.DestAddress</td>
<td>#GetRateModel.DestCity</td>
<td>#GetRateModel.DestState miles</td>
</tr>
</table>
Controller Functions
[HttpPost]
public ActionResult GetDetail(string origin, string destination, string billTo, bool flat, bool rpm)
{
GetRateModel total = new GetRateModel
{
OriginName = "Name",
OriginAddress = "Address",
OriginCity = "City",
OriginState = "State",
DestName = "Name",
DestAddress = "Address",
DestCity = "City",
DestState = "State",
};
return PartialView("Index", total);
}
Model
public class GetRateModel
{
public string OriginName { get; set; }
public string OriginAddress { get; set; }
public string OriginCity { get; set; }
public string OriginState { get; set; }
public string DestName { get; set; }
public string DestAddresss { get; set; }
public string DestCity { get; set; }
public string DestState { get; set; }
This works when I declare static variables in my model, but I need to set these to an instance of the class instead. How would I wire my table to update based on an instance of my model? I've seen a solution that creates rows with a foreach loop and lists in the model, but I don't think that would be the best solution for my problem.
You need to update your view as following:
#* try specifying the fully qualified name of your Model class here if the following line gives error *#
#model GetRateModel
<script type="text/javascript">
$(document).ready(function () {
$("#getRates").click(function () {
$.ajax(
{
type: "POST",
url: '#Url.Action("GetDetail", "ControllerName")',
data: { origin: "", destination: "", billTo: "", flat: true, rpm: true }
}).success(function () {
alert("hit!")
//$('#MyTable').load(location.href + " #MyTable")
$('#MyTable').html(response);
});
});
});
</script>
<button type="button" id="getRates" class="button getRates">Get Rates</button>
<br /><br /><br />
<div id="MyTable">
#if (Model != null)
{
<table>
<tr>
<th width="15%">Name</th>
<th width="15%">Address</th>
<th width="15%">City</th>
<th width="15%">State</th>
</tr>
<tr>
<td>#Model.OriginName</td>
<td>#Model.OriginAddress</td>
<td>#Model.OriginCity</td>
<td>#Model.OriginState miles</td>
</tr>
<tr>
<td>#Model.DestName</td>
<td>#Model.DestAddress</td>
<td>#Model.DestCity</td>
<td>#Model.DestState miles</td>
</tr>
</table>
}
</div>
For more information: https://learn.microsoft.com/en-us/aspnet/mvc/overview/views/dynamic-v-strongly-typed-views
Also, I strongly suggest that you use a different View file to render the table data otherwise whenever you click on the button, your final html in browser will contain repeated script tags and repeated buttons.
Related
I have a page (asp.net 6 mvc web app with identity) with a list of users and I want to have a search bar to filter those users by their emails but I have no idea how to do it
Admin controller
public class AdminController : Controller
{
private readonly ILogger<AdminController> _logger;
private readonly UserManager<ApplicationUser> _userManager;
private readonly RoleManager<IdentityRole> _roleManager;
public AdminController(ILogger<AdminController> logger, UserManager<ApplicationUser> userManager, RoleManager<IdentityRole> roleManager)
{
_logger = logger;
_roleManager = roleManager;
_userManager = userManager;
}
public async Task<IActionResult> ListOfUsersAndRoles()
{
var users = await _userManager.Users.ToListAsync();
var userRolesViewModel = new List<UserRolesViewModel>();
foreach (ApplicationUser user in users)
{
var thisViewModel = new UserRolesViewModel();
thisViewModel.UserId = user.Id;
thisViewModel.Email = user.Email;
thisViewModel.Name = user.UserName;
thisViewModel.Roles = await GetUserRoles(user);
userRolesViewModel.Add(thisViewModel);
}
return View(userRolesViewModel);
}
ListOfUsersAndRoles view
<h1>List of users and roles</h1>
<table class="table">
<thead>
<tr>
<th>Email</th>
<th>Role</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach (var user in Model)
{
<tr>
<td>#user.Email</td>
<td>#string.Join(" , ", user.Roles.ToList())</td>
<td>
<a class="btn btn-primary" asp-controller="Admin" asp-action="ModifyRole" asp-route-userId="#user.UserId">Modify role</a>
</td>
</tr>
}
</tbody>
</table>
This must be so easy to code but as a beginner I'm lost, the tutorials that I'm watching are either for older versions of asp.net or they don't use mvc, EF, identity and so on so instead of learning, I'm actually getting more and more confused. From what I'm seeing, I think javascript is necessary and I have no knowledge in javascript
Any videos, websites or advices are welcome
Since you have no knowledge in javascript, So I try to write a simple demo to achieve your goal without javascript, Please refer to this:
ViewModel
public class SearchViewModel
{
public string Email { get; set; }
public IEnumerable<string> Role { get; set; }
public string UserId { get; set; }
}
Controller
public class SearchController : Controller
{
private readonly RoleManager<IdentityRole> roleManager;
//if you don't use custom identityuser, you just use UserManager<IdentityUser> here
private readonly UserManager<AppUser> userManager;
public SearchController(UserManager<AppUser> userManager, RoleManager<IdentityRole> roleManager)
{
this.userManager = userManager;
this.roleManager = roleManager;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Index(SearchViewModel model)
{
var user = await userManager.FindByEmailAsync(model.Email);
if(user != null)
{
var role = await userManager.GetRolesAsync(user);
SearchViewModel viewModel = new SearchViewModel()
{
Role = role,
Email = user.Email,
UserId = user.Id
};
return View(viewModel);
}
else
{
ViewBag.result = "User not found";
return View();
}
}
}
Index
#model SearchViewModel
<h1>List of users and roles</h1>
<form asp-controller="Search" asp-action="Index" method="post">
<input asp-for="#Model.Email" />
<button type="submit">search</button>
</form>
<table class="table">
<thead>
<tr>
<th>Email</th>
<th>Role</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#if (#Model!=null)
{
<tr>
<td>#Model.Email</td>
<td>
#foreach (var role in #Model.Role)
{
<div>#role</div>
}
</td>
<td>
<a class="btn btn-primary" asp-controller="Admin" asp-action="ModifyRole" asp-route-userId="#Model.UserId">Modify role</a>
</td>
</tr>
}
else
{
<h3> #ViewBag.result</h3>
}
</tbody>
</table>
Demo:
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
When I loading table I got ajax error in datatable.(.net)
This is my data table code
<table id="productsTable" class="table table-striped table-bordered">
<thead>
<tr>
<th>Name</th>
<th>Code</th>
<th>Price</th>
<th>No of Products</th>
</tr>
</thead>
</table>
<link href="//cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" />
<link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap.min.css" rel="stylesheet" />
#section scripts{
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap.min.js"></script>
<script>
$(document).ready(function () {
$('#productsTable').DataTable({
"ajax": {
"url": "/Products/GetData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Name" },
{ "data": "Code" },
{ "data": "Price" },
{ "data": "Available" }
]
});
});
</script>
}
this is my controller
public ActionResult GetData()
{
using (DBModel db = new DBModel())
{
List<product> proList = db.products.ToList<product>();
return Json(new { data = proList }, JsonRequestBehavior.AllowGet);
}
}
product is my db table ,
this is the model
public partial class product
{
public int ProductId { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public decimal Price { get; set; }
public Nullable<int> Available { get; set; }
public byte[] is_deleted { get; set; }
}
Error Looks like
DataTables warning: table id=productsTable - Ajax error. For more information about this error, please see http://datatables.net/tn/7
Click here: https://dotnetfiddle.net/S7KWOg
I did not get an error with this:
View
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index4</title>
#*added this css*#
<style>
body {
padding-left: 50px;
width: 80%;
}
</style>
#*removed the bootstrap for better dataTable styling*#
#*putting all your scripts in the head*#
<link href="//cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" />
#*<link href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap.min.css" rel="stylesheet" />*#
#*added this script*#
<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css" rel="stylesheet" />
#*need this jquery script*#
<script src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
#*<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap.min.js"></script>*#
<script>
$(document).ready(function () {
$('#productsTable').DataTable({
"ajax": {
//using home controller instead of products
"url": "/Home/GetData",
//"url": "/Products/GetData",
"type": "GET",
"datatype": "json"
},
"columns": [
{ "data": "Name" },
{ "data": "Code" },
{ "data": "Price" },
{ "data": "Available" }
]
});
});
</script>
</head>
<body>
<table id="productsTable" class="table table-striped table-bordered display">
#*added display class*#
<thead>
<tr>
<th>Name</th>
<th>Code</th>
<th>Price</th>
<th>No of Products</th>
</tr>
</thead>
</table>
#section scripts{
#*moved these scripts to the head*#
}
</body>
</html>
Controller/Model
public class product
{
public int ProductId { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public decimal Price { get; set; }
public Nullable<int> Available { get; set; }
public byte[] is_deleted { get; set; }
}
public class HomeController : Controller
{
public ActionResult GetData()
{
//using (DBModel db = new DBModel())
//{
// List<product> proList = db.products.ToList<product>();
// return Json(new { data = proList }, JsonRequestBehavior.AllowGet);
//}
List<product> proList = new List<product>{ new product { Available = 1, Code = "Code1", is_deleted = new byte[1],
Name = "Name1", Price = 1.27M, ProductId = 1 },
new product { Available = 2, Code = "Code2", is_deleted = new byte[2],
Name = "Name2", Price = 1.28M, ProductId = 2 },
new product { Available = 3, Code = "Code3", is_deleted = new byte[3],
Name = "Name3", Price = 1.29M, ProductId = 3 } };
return Json(new { data = proList }, JsonRequestBehavior.AllowGet);
}
public ActionResult Index4()
{
return View();
}
This is our Home Index:
#model ELearning.Data.ELearningEgitimDTO
#{
ViewBag.Title = "Home Page";
}
<div class="jumbotron">
#if (TempData["message"] != null)
{
<div class="alert alert-info" role="alert">#TempData["message"]</div>
}
<div>
<div>
#if (Model.EgitimTuru == 5)
{
<h1>Yangın Eğitimi</h1>
}
<table class="table table-responsive">
<tr>
<td width="20%">Şirket Adı:</td>
<td width="80%">#Model.Name</td>
</tr>
<tr>
<td>Eğitimi Veren:</td>
<td>#Model.PersonelAdi</td>
</tr>
<tr>
<td>Eğitim Tarihi:</td>
<td>#Model.Tarih</td>
</tr>
</table>
</div>
<div>
<table class="table table-responsive">
<tr>
<td>Eğitim Konuları:</td>
</tr>
#foreach (var konu in Model.Adi)
{
<tr>
<td><ul><li>#konu</li></ul></td>
</tr>
}
</table>
</div>
</div>
<p class="text-right"><button onclick="getStartDate()" class="btn btn-primary btn-lg ">Eğitime Başla »</button></p>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function getStartDate() {
$.post("/Video/GetStartDate",
{
PerNr: #Model.PerNr,
StartDate: "",
EndDate: "",
EgitimFilesId: #Model.FileId
});
}
</script>
</div>
This is Video Index:
#model WebApplication3.Models.VideoLogsModel
#{
ViewBag.Title = "Video Page";
}
<div class="jumbotron">
<div>Eğitime başlanan zaman:</div>
<div id="startdate"></div>
<div class="col-md-12 text-center">
<video controls controlslist="nodownload" id="videoPlayer" width: 100% height: auto>
<source src="~/Video/GetVideo" type="video/mp4">
</video>
</div>
<br />
<div class="text-right">
<p id="button" onclick="egitimiBitir()" class="btn btn-danger btn-lg ">Eğitimi Bitir</p>
</div>
<script type="text/javascript">
var vid = document.getElementById("videoPlayer");
var button = document.getElementById("button");
if (vid.played) {
setInterval(function () { vid.pause(); }, 30000);
}
vid.addEventListener("ended", function() {
button.className = "btn btn-success btn-lg "
});
function egitimiBitir() {
if (vid.ended) {
$.post("/Video/GetEndDate",
{
PerNr: #Model.PerNr,
StartDate= "",
EndDate: "",
EgitimFile sId: #Model.EgitimFilesId
});
}
else {
document.getElementById("message").innerHTML = "Video tamamlanmadan eğitimi bitiremezsiniz.."
}
}
</script>
</div>
This is our main model:
public class ELearningEgitimDTO
{
public ELearningEgitimDTO() { }
public ELearningEgitimDTO(string PerNr, int ID)
{
this.ID = ID;
this.PerNr = PerNr;
}
public int ID { get; set; }
public string PerNr { get; set; }//katılımcıID
public string Name { get; set; }//şirket adı
public int EgitimTuru { get; set; }
public DateTime Tarih { get; set; }//egitim tarihi
public string PersonelAdi { get; set; } // eğitimi veren
public int FileId { get; set; }
public string FileName { get; set; }
public string[] Adi { get; set; }
}
This is our model:
public class VideoLogsModel
{
public int EgitimFilesId { get; set; }
public int PerNr { get; set; }
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
}
This is our Home Controller:
public class HomeController : Controller
{
public ActionResult Index(int EgitimId=4, string PerNr="2")
{
ELearningService service = new ELearningService();
ELearningEgitimDTO egitim = new ELearningEgitimDTO(PerNr, EgitimId);
return View(service.getInfo(egitim)); //eğitim bilgileri istenirken egitimId ve egitim kullanıcıdaki eğitmenin perNr si verilmeli!!
}
}
This is our Video Controller:
public class VideoController : Controller
{
public ActionResult Index(VideoLogsModel model)
{
return View(model);
}
public ActionResult GetVideo()
{
var memoryStream = new MemoryStream(System.IO.File.ReadAllBytes(#"C:\Users\cyare\Desktop\videoplayback.mp4"));
//byte[] bytes = System.IO.File.ReadAllBytes(#"C:\Users\melik.DESKTOP-LQQAB68\Desktop\videoplayback.mp4");
//System.IO.File.WriteAllBytes(#"C:\Users\melik.DESKTOP-LQQAB68\Desktop\videoplayback.mp4", bytes);
return new FileStreamResult(memoryStream, "video/mp4");
}
/* [HttpPost]
public ActionResult GetStartEndDate(VideoLogsModel logs)
{
DateTime startDate = logs.StartDate; //database de uygun tabloya yazılır
return RedirectToAction("Index", "Video");
}*/
[HttpPost]
public ActionResult GetStartDate(VideoLogsModel model)
{
model.StartDate = System.DateTime.Now;
ELearningDosyaKullaniciDTO user = new ELearningDosyaKullaniciDTO();
user.egitimFileID = model.EgitimFilesId;
user.egitimKullanıcı = model.PerNr;
user.startDate = model.StartDate;
ELearningService service = new ELearningService();
//service.CreateLogs(user);
//return RedirectToAction("Index","Video",model);*/
return RedirectToAction("Index", model);
}
[HttpPost]
public ActionResult GetEndDate(VideoLogsModel model)
{
model.EndDate = System.DateTime.Now;
ELearningDosyaKullaniciDTO user = new ELearningDosyaKullaniciDTO();
user.egitimFileID = model.EgitimFilesId;
user.egitimKullanıcı = model.PerNr;
user.endDate = model.EndDate;
ELearningService service = new ELearningService();
service.UpdateLogs(user);
TempData.Add("message", String.Format("Eğitiminiz Tamamlanmıştır!"));
return RedirectToAction("Index", "Home");
}
}
My question is how can i pass the model from home index to video controller and then to video index?
Video Index doesn't run. It goes to video index but then it runs home index again.
Also it runs egitimibitir() function before button's onclick function.
You send an ajax request to your service. (endpoint => GetEndDate) I think you can change your code like that,
$.ajax({
type: "POST",
url: "/Video/GetEndDate", //your reqeust url
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
// your data here
}),
success: function (data) {
// check state of data
// after check window.location = // redirect url
},
error: function (data) {
// handle exception
}
});
You can change your controller method to a data controller. (not an ActionResult. create a custom result object which include your data and your success state. you can use this custom result object every ajax requests for return state and data). If an exception occurs while executing "GetEndDate" method, you need to handle exception and you need to show it to client. You send exception or your success complete response to to client(view). (you can handle your exception data in ajax error: function)
I am using a partial view "_studentList" in a View "SearchStudent". In my View i have a textfield and a search button and i am showing list of students in my partial view.
My View is like as follow:
#model Practice_SQL_Validation_ALL.Models.SearchViewModel
#{
ViewBag.Title = "SearchStudent";
}
<h2>SearchStudent</h2>
<nav class="navbar navbar-default">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand">Search</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<form class="navbar-form navbar-left" role="search">
<div class="form-group">
<input type="text" class="form-control" id="txtserch" placeholder="Enter Roll No or Name">
#*#Html.EditorFor(model => model.SEARCHCRITERA.VALUE, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter Roll No or Name" } })*#
</div>
<button id="preview" type="button" class="btn btn-default">Search</button>
</form>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<div id="result">
#Html.Partial("_StudentList", Model.STUDENTLIST)
</div>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
jQuery.ready(function () {
$("#result").hide();
$("#preview").click(function () {
//$("#div1").hide();
$("#result").show();
});
});
$("#preview").click(function () {
var jsonObject = {
"returnUrl": $('#txtserch').val()
};
jQuery.ajax({
type: "POST",
url: "SearchStudent",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(jsonObject),
success: function (data) { alert("Success"); },
failure: function (errMsg) {
alert("Error");
}
});
});
</script>
And my Partial View is like as follow:
#model IEnumerable<Practice_SQL_Validation_ALL.Models.Student>
#*<p>
#Html.ActionLink("Create New", "Create")
</p>*#
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.ROLLNUMBER)
</th>
<th>
#Html.DisplayNameFor(model => model.NAME)
</th>
<th>
#Html.DisplayNameFor(model => model.ADDRESS)
</th>
<th>
#Html.DisplayNameFor(model => model.PHONE)
</th>
<th>
#Html.DisplayNameFor(model => model.CLASS)
</th>
<th>
#Html.DisplayNameFor(model => model.ISNEW)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.ROLLNUMBER)
</td>
<td>
#Html.DisplayFor(modelItem => item.NAME)
</td>
<td>
#Html.DisplayFor(modelItem => item.ADDRESS)
</td>
<td>
#Html.DisplayFor(modelItem => item.PHONE)
</td>
<td>
#Html.DisplayFor(modelItem => item.CLASS)
</td>
<td>
#Html.DisplayFor(modelItem => item.ISNEW)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
#Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
</tr>
}
</table>
My ViewModel is like as follow:
namespace Practice_SQL_Validation_ALL.Models
{
public class SearchViewModel
{
private SearchCriteria searchcriteria = null;
private List<Student> studentlist = null;
public SearchCriteria SEARCHCRITERA
{
set
{
searchcriteria = value;
}
get
{
return searchcriteria;
}
}
public List<Student> STUDENTLIST
{
set
{
studentlist = value;
}
get
{
return studentlist;
}
}
public SearchViewModel()
{
searchcriteria = new SearchCriteria();
studentlist = new List<Student>();
}
}
public class SearchCriteria
{
[Display(Name = "Criteria")]
public string CRITERIA { get; set; }
[Display(Name = "Value")]
public string VALUE { get; set; }
}
public class Student
{
#region Properties
private bool m_isnew = true;
[Required]
[Display(Name = "Roll Number")]
public string ROLLNUMBER { get; set; }
[Required]
[Display(Name = "Name")]
public string NAME { get; set; }
//[Required]
[Display(Name = "Address")]
public string ADDRESS { get; set; }
//[Required]
[Display(Name = "Phone#")]
public string PHONE { get; set; }
[Display(Name = "Class")]
public string CLASS { get; set; }
[Display(Name = "Edit Mode")]
public bool ISNEW { get { return m_isnew; } set { m_isnew = value; } }
#endregion
}
}
My StudentController is as follow:
namespace Practice_SQL_Validation_ALL.Controllers
{
public class StudentController : Controller
{
public ActionResult SearchStudent()
{
SearchViewModel obj = new SearchViewModel();
ViewBag.Count = 0;
return View(obj);
}
[HttpPost]
//[AllowAnonymous]
//[ValidateAntiForgeryToken]
//[ChildActionOnly]
public ActionResult SearchStudent(string returnUrl)
{
SearchViewModel obj = new SearchViewModel();
//DAS db = new DAS();
//list = db.SearchStudentwithCriteria("RollNo", "");
//return PartialView()
obj.SEARCHCRITERA.VALUE = "Some";
obj.STUDENTLIST.Add(new Student { ADDRESS = "Address", ROLLNUMBER = "3160", NAME = "Awais", CLASS = "A", PHONE = "Phone" });
//return View(list);
ViewBag.Count = obj.STUDENTLIST.Count;
//return View(obj);
return PartialView("_StudentList", obj);
//return PartialView("_StudentList", list);
//return PartialView("_StudentList", list);
}
}
}
I want that if I click search button then ajax call SearchStudent Post function and return collection that should be displayed on partial view. Till now function is being called but response is not being returned to the view or partialview. As i am showing alertbox in both cases success and failure but system does not show alertbox in anycase. What am i doing wrong? Any help would be greatly appreciated! Please let me know if you need any more information.
Very Thanks in Advance.
Everything seems fine just the ajax succes you have to put the content like this
$.ajax({
url: "SearchStudent",
data: { "returnUrl": $('#txtserch').val()},
type: "POST",
cache: false,
success: function (data) {
$("#result").html(data); //********* This is where you have put the result into, because in success you will get the HTML
},
error: function () {
}
});
Made some changes as follow and got my issue fixed.
In Controller function "SearchStudent" returned partialview with collection.
public ActionResult SearchStudent(string returnUrl)
{
SearchViewModel obj = new SearchViewModel();
obj.SEARCHCRITERA.VALUE = "Some";
obj.STUDENTLIST.Add(new Student { ADDRESS = "Address", ROLLNUMBER = "3160", NAME = "Awais", CLASS = "A", PHONE = "Phone" });
ViewBag.Count = obj.STUDENTLIST.Count;
return PartialView("_StudentList", obj.STUDENTLIST);
}
And changed ajax call as follow:
jQuery.ajax({
type: "POST",
url: "SearchStudent",
//dataType: "json",
cache: false,
//context:
contentType: "html",
data: JSON.stringify(jsonObject),
success: function (data) { $("#result").html(data); },
failure: function (errMsg) {
$("#result").html("Error");
}
});
I think problem was majorly in ajax call. As i was returning html content from controller function but in ajax call i have mentained contentType and datatype properties as Json. That's why HTML could not been shown on success.