Search bar for an existing list - javascript

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:

Related

Updating HTML table with instance variables of C# class (jQuery, AJAX)

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.

How to pass data between views and controller?

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)

Object Moved Here - RedirectToAction

Again, after tiresome attempts to solve this annoying issue, I am back here. I am experiencing an "Object moved here" on my view in my MVC5 application after some return RedirectToAction("Index", "Roles", model); action on my controller.
I have considered solutions from the following links:
RedirectToAction and "Object moved to here" error
ASP.NET MVC Website: Object Moved to Here
https://forums.asp.net/t/1643235.aspx?+Object+moved+to+here+problem
but none are applicable to my problem.
Before anyone marks this as a duplicate, please consider the scenario below:
But now the weird thing is that after I have clicked on the 'here' link and it now renders my view - it has a horizontal split screen showing the correct display of my view on top and below the view that throws an Http Error Code - in this case its Error Code 500 : Internal Server Error.
The reason why I am getting the http status code error is due to this unanswered question here (one of many) :
Failed to load resource: Uncaught TypeError: $(...).select2 is not a function
But that is besides the point right now.
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create([Bind(Include = "Name,Description")] ApplicationRole model)
{
try
{
if (ModelState.IsValid)
{
var role = new ApplicationRole()
{
Name = model.Name,
Description = model.Description
};
var roleManager = new RoleManager<ApplicationRole>(new RoleStore<ApplicationRole>(db));
var result = await roleManager.CreateAsync(role);
if (result.Succeeded)
{
return RedirectToAction("Index", "Roles", model);
}
else
{
AddErrors(result);
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
// If we got this far, something failed, redisplay form
return View(model);
}
//Below is my index method in my Roles controller which is the action that redirection needs to route to:
[Route("/Roles")]
public ActionResult Index()
{
if (TempData["StatusMessage"] != null)
{
ViewBag.StatusMessage = TempData["StatusMessage"].ToString();
}
else
{
ViewBag.StatusMessage = "";
}
var roles = db.Roles.ToList();
return View("Index", roles);
}
//GET method to create view
public ActionResult Create()
{
return View();
}
View:
#model IEnumerable<User_Manager_Interface.Models.ApplicationRole>
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
#if (ViewBag.StatusMessage != null)
{
if (ViewBag.StatusMessage != "")
{
string tmp = ViewBag.StatusMessage;
if (tmp.Contains("error"))
{
<div class="notification msgerror">
<a class="close"></a>
<p>#ViewBag.StatusMessage</p>
</div>
}
else
{
<div class="notification msgsuccess">
<a class="close"></a>
<p>#ViewBag.StatusMessage</p>
</div>
}
}
}
<br />
#Html.ActionLink("Create New", "Create", "Roles", new object { }, new { #class = "stdbtn" })
<br />
<br />
<div class="contenttitle radiusbottom0">
<h2 class="table"><span>Roles</span></h2>
</div>
<table cellpadding="0" cellspacing="0" border="0" class="stdtable" id="dyntable">
<colgroup>
<col class="con0" />
<col class="con1" />
<col class="con0" />
</colgroup>
<thead>
<tr>
<th class="head1">Name</th>
<th class="head0">Description</th>
<th class="head1">Options</th>
</tr>
</thead>
<tfoot>
<tr>
<th class="head1">Name</th>
<th class="head0">Description</th>
<th class="head1">Options</th>
</tr>
</tfoot>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
#Html.ActionLink("Details", "Details", new { id = item.Id }) |
#Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</tbody>
</table>
#section Scripts {
#Scripts.Render("~/bundles/tables")
}
Model:
public class ApplicationRole : IdentityRole
{
[Display(Name = "Description")]
[StringLength(100, MinimumLength = 5)]
public string Description { get; set; }
}
"Error" Controller:
public class ErrorController : Controller
{
//
// GET: /Error/
public ActionResult Index(int statusCode, Exception exception)
{
Response.StatusCode = statusCode;
return View();
}
}
"Error" View:
#{
ViewBag.Title = Response.StatusCode;
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2 style="visibility:hidden">#ViewBag.Title</h2>
<div class="errorWrapper">
<h2>An internal server error #ViewBag.Title has occurred</h2>
<h1 class="pageErrorTitle" style="color:red">Error #ViewBag.Title - Page Not Found</h1>
<h3 style="color:black">You may have clicked an expired link or mistyped the address.</h3>
<br />
<a class="default" href="javascript:history.back()">Back to Previous Page</a> <a class="default" href="http://localhost:53648">Return to Dashboard</a>
</div>
Please see screenshots for more visual clarity:
Update:
According to #Munzer 's answer below, I tried to change my Index action method to take in the model route value seeing as though I am passing it in my return statement. See below:
public async Task<ActionResult> Create(ApplicationRole model)
{
if (ModelState.IsValid)
{
var role = new ApplicationRole()
{
Name = model.Name,
Description = model.Description
};
var roleManager = new RoleManager<ApplicationRole>(new RoleStore<ApplicationRole>(db));
var result = await roleManager.CreateAsync(role);
if (result.Succeeded)
{
//return RedirectToAction("Index", "Roles", model);
return RedirectToAction("SuccessfullyAddedNewRole", "Roles", model);
}
else
{
AddErrors(result);
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
public ActionResult SuccessfullyAddedNewRole(ApplicationRole model)
{
return View(model);
}
But the error still persists. I have tried everything I can think of.
I think the error is here
return RedirectToAction("Index", "Roles", model);
you are passing route values but your index action doesn't accept any, it generate the value itself, you can simple do this instead
return RedirectToAction("Index", "Roles");,
and your index will query the new model, if you want to pass the model, you need to edit your index action accordingly, to accept role model.
Solution can be found on this SO post of mine. Fixed everything :-)
GET http://localhost/Roles/Create 500 (Internal Server Error)

using partial view in a view and getting data to partial view

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.

String values not being picked up by array in AngularJS

I am currently working on an accounting project and I am experiencing a stupid problem.
I enter the values in text boxes and I click on Add Person button, the values get added but when I click Save to Database button the multiple added values get pushed into database. I am able to insert multiple values in the database but unable to call the multiple entries from the SQL server back again onto my UI.
I have multiple same first names in my table of SQL server and I want to pick up all the values which have the same first name and populate them in $scope.arr I defined in angular code.
When I pass an integer value in my $scope.GetPerson() method, I get the desired result and my array ($scope.arr) gets populated with all the values having the same CustomerCode but when I pass a string value i.e, FirstName in GetPerson method, my array($scope.arr) doesn't get populated with the same First Name values that were placed into the database.
I want the experts to look into this problems and guide me where am I actually doing the mistake.`
My Model:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace TestProj.Models
{
public class TestModel
{
public int ID { get; set; }
public int CustomerCode { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public decimal Debit { get; set; }
public decimal Credit { get; set; }
}
}
My Angular JS script:
var app = angular.module("TestApp", []);
app.controller("TestCtrl", function ($scope, TestService) {
$scope.arr = [];
GetAllPers();
function GetAllPers() {
var getPersData = TestService.getPersons();
getPersData.then(function (Persons) {
$scope.persons = Persons.data;
}, function () {
alert('Error in getting Person records');
});
}
$scope.addPerson = function () {
var obj = {
CustomerCode: $scope.customercode,
FirstName: $scope.firstname,
LastName: $scope.lastname,
Debit: $scope.debit,
Credit: $scope.credit,
};
$scope.arr.push(obj);
};
$scope.savePerson = function () {
var TestData = TestService.AddPer($scope.arr);
TestData.then(function (msg) {
$scope.customercode = "";
$scope.firstname = "";
$scope.lastname = "";
$scope.debit = "";
$scope.credit = "";
GetAllPers();
alert(msg.data);
for (var i = 0; i < $scope.arr.length; i++) {
$scope.arr.pop();
}
}, function () {
alert('Error In Adding Person');
});
};
$scope.GetPerson = function (test) {
var getTestData = TestService.getPers(test.FirstName);
getTestData.then(function (_test) {
$scope.arr = _test.data;
}, function () {
alert('Error in getting person records');
});
}
});
app.service("TestService", function ($http) {
this.getPersons = function () {
return $http.get("/Test/GetAllPers");
}
this.AddPer = function (person) {
var response = $http({
method: "post",
url: "/Test/AddPerson",
data: JSON.stringify(person),
dataType: "json",
});
console.log(response);
return response;
}
this.getPers = function (persname) {
var response = $http({
method: "post",
url: "/Test/GetPersonByFName",
params: {
firstname: JSON.stringify(persname)
}
});
return response;
}
});
My C# controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TestProj.Models;
namespace TestProj.Controllers
{
public class TestController : Controller
{
TestContext dc = new TestContext();
// GET: Test
public ActionResult Index()
{
return View();
}
public JsonResult GetAllPers()
{
var personList = dc.TestModels.ToList();
return Json(personList, JsonRequestBehavior.AllowGet);
}
public JsonResult GetPersonByFName(string firstname)
{
var q = (from ab in dc.TestModels.Where(b => b.FirstName == firstname) select ab);
return Json(q, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public string AddPerson(List<TestModel> test)
{
bool val = false;
foreach (var t in test)
{
if (t != null)
{
dc.TestModels.Add(t);
val = true;
}
else
{
val = false;
}
}
dc.SaveChanges(); //save context at the end, when no error occurs
if (val == true)
{
return "Success";
}
else
{
return "Failed";
}
}
}
}
My HTML:
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div ng-controller="TestCtrl">
<form>
<button class="btn" data-toggle="modal" data-target="#myModal">Show records</button><br />
Customer Code: <input class="form-control" ng-model="customercode" /><br />
FirstName: <input class="form-control" ng-model="firstname" /><br />
LastName: <input class="form-control" ng-model="lastname" /><br />
Debit: <input class="form-control" ng-model="debit" /><br />
Credit: <input class="form-control" ng-model="credit" /><br />
<button class="btn btn-success" ng-click="addPerson()">Add Person</button>
<button class="btn btn-success" ng-click="savePerson()">Save To DB</button>
#*Table for showing pushed values*#
<table class="table table-bordered">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Debit</th>
<th>Credit</th>
</tr>
<tr ng-repeat="a in arr">
<td>{{a.CustomerCode}}</td>
<td>{{a.FirstName}}</td>
<td>{{a.LastName}}</td>
<td>{{a.Debit}}</td>
<td>{{a.Credit}}</td>
</tr>
</table>
#*Modal popup*#
<div class="modal fade" role="dialog" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4>Persons</h4>
</div>
<div class="modal-body">
<label class="control-label col-md-2" style="width: auto">Search:</label>
<div class="col-md-8">
<input class="form-control" ng-model="searchfor" />
</div><br />
<table class="table table-hover">
<tr>
<td><b>First Name</b></td>
<td><b>Last Name</b></td>
<td><b>Debit</b></td>
<td><b>Credit</b></td>
<td><b>Select</b></td>
</tr>
<tr ng-repeat="b in persons | filter:searchfor ">
<td>{{b.CustomerCode}}</td>
<td>{{b.FirstName}}</td>
<td>{{b.LastName}}</td>
<td>{{b.Debit}}</td>
<td>{{b.Credit}}</td>
<td>
<button type="button" class="btn btn-success" ng-click="GetPerson(b)" data-dismiss="modal">Select</button>
</td>
</tr>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" data-toggle="modal" data-target="#myModal">Okay</button>
</div>
</div>
</div>
</div><br />
</form>
</div>
<script src="~/Scripts/MyAngular/Module.js"></script>
The issue is with your getPers(). Adding JSON.stringfy() adds " to your string.
It should be used like this :
this.getPers = function (persname) {
var response = $http({
method: "post",
url: "/Test/GetPersonByFName",
params: {
firstname: persname
}
});
return response;
}

Categories

Resources