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

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.

Related

How can i make the condition so that after read the card in text area, it updates the record that exists before it creates a new one?

https://prnt.sc/IsuRy9OhDic7 Screenshot To check what I am talking about.
Before it enters a new record it should save the TimeOut("HoraSaida") in the previous record.
I already did my research but I couldn't find anything that helps me out.
It reads the card in a text area with event change if it changes it saves the card number, it gets the date of record and the time in(hora entrada).
When it reads the second time it should save in the field time out (hora saida) before it enters a new record.
The Last field is a calculated field that gives the worked hours of that day.
Model
public partial class entradas_saidas
{
public int IdE_S { get; set; }
public Nullable<int> IdCartao { get; set; }
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> DataRegisto { get; set; }
[DisplayFormat(DataFormatString = "{0:HH:mm:ss}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> HoraEntrada { get; set; }
[DisplayFormat(DataFormatString = "{0:HH:mm:ss}", ApplyFormatInEditMode = true)]
public Nullable<System.DateTime> HoraSaida { get; set; }
public Nullable<int> HoraDiarias { get; set; }
}
Controller
[HttpPost]
public ActionResult AddReport(entradas_saidas es)
{
using (EMSistec bd = new EMSistec())
{
try
{
bd.entradas_saidas.Add(es);
bd.SaveChanges();
string message = "SUCCESS";
return Json(new { msg = message, JsonRequestBehavior.AllowGet });
}
catch (Exception)
{
String message = "ERROR";
return Json(new { msg = message, JsonRequestBehavior.AllowGet });
}
}
}
VIEW with Script
#using employeeManagement.Models;
#using PagedList.Mvc;
#model PagedList.IPagedList<employeeManagement.Models.entradas_saidas>
#*#model IEnumerable<employeeManagement.Models.entradas_saidas>*#
#{
ViewBag.Title = "EntradasSaidas";
}
<h2>EntradasSaidas</h2>
<h4 id="msg" style="color:red">#ViewBag.msg</h4>
#Html.Label("lblsearch", "Leitura do Cartão:", htmlAttributes: new { #class = "control-label col-md-2 " })
<textarea style="color:dodgerblue" id="readONchange"></textarea>
<br />
<p>
#Html.ActionLink("Create New", "AddEntradasSaidas")
</p>
<table class="table">
<tr>
<th>
#
#*#Html.DisplayNameFor(model => model.IdE_S)*#
</th>
<th>
#Html.ActionLink("Número Cartão", "EntradasSaidas", new { order = ViewBag.idcartao })
#*#Html.DisplayNameFor(model => model.IdCartao)*#
</th>
<th>
Data Registo
#*#Html.DisplayNameFor(model => model.DataRegisto)*#
</th>
<th>
Hora Entrada
#*#Html.DisplayNameFor(model => model.HoraEntrada)*#
</th>
<th>
Hora Saída
#*#Html.DisplayNameFor(model => model.HoraSaida)*#
</th>
<th>
Horas Diárias
#*#Html.DisplayNameFor(model => model.HoraDiarias)*#
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.IdE_S)
</td>
<td>
#Html.DisplayFor(modelItem => item.IdCartao)
</td>
<td>
#Html.DisplayFor(modelItem => item.DataRegisto)
</td>
<td>
#Html.DisplayFor(modelItem => item.HoraEntrada)
</td>
<td>
#Html.DisplayFor(modelItem => item.HoraSaida)
</td>
<td>
#Html.DisplayFor(modelItem => item.HoraDiarias)
</td>
<td>
#Html.ActionLink("Edit", "EditEntradasSaidas", new { id = item.IdE_S }) |
#*#Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |*#
#*#Html.ActionLink("Delete", "DeleteMorada", new { id = item.IdMorada })*#
#Html.ActionLink("Delete", null, null, new { id = item.IdE_S, name = "dellink" })
</td>
</tr>
}
</table>
#((Model.PageNumber > Model.PageCount) ? 1:Model.PageNumber) de #Model.PageCount páginas.
#Html.PagedListPager(Model, (page) => Url.Action("EntradasSaidas", new { page, order = ViewBag.order }))
#*#section readcard{
<script>
function readCard() {
alert("HELLO");
}
</script>
}*#
#section readcard{
<script>
$(function () {
$("#readONchange").change(function () {
var param1 = new Date();
var param2 = param1.getDate() + '/' + (param1.getMonth() + 1) + '/' + param1.getFullYear();
var param3 = param1.getHours() + ':' + param1.getMinutes() + ':' + param1.getSeconds();
var es = {};
es.IdCartao = $("#readONchange").val();
es.DataRegisto = param2;
if (es.IdCartao == "#readONchange" && es.HoraEntrada == null) {
es.HoraEntrada = param3;
} else {
es.HoraSaida = param3;
}
alert("AGORA AQUI")
$.ajax({
type: "POST",
url: '#Url.Action("AddReport")',
data: '{es: ' + JSON.stringify(es) + '}',
dataType: "json",
contentType: "application/json; charset=utf-8",
sucess: function () {
alert("Dado inserido com sucesso");
},
error: function () {
alert("ERRO! Nao foi possivel");
}
});
});
});
</script>
}
#section esDelete{
<script>
$(function () {
$("[name='dellink']").click((evt) => {
evt = evt ? evt : window.event;
evt.preventDefault();
if (!confirm("Tem a certeza que quer apagar o registo?")) return false;
$.ajax({
url: '#Url.Action("DeleteEntradasSaidas")',
dataType: 'json',
data: { id: evt.target.id },
success: function (data) {
console.log(JSON.stringify(data));
if (data.msg == "Registo apagado com sucesso!") $(evt.target).closest('tr').remove();
$("h4").html(data.msg);
},
error: function () { alert("Erro ao apagar registo!");}
});
});
});
</script>
}

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.

Passing a Parameter to Javascript Function for ajax in mvc

I have a problem that I cannot handle. I have a ASP.NET MVC application. It's purpose is to listing items inside. These items are project activity with financial report of it. At the view, users suppose to view the financial information of the project activity and edit some values. Here is the view:
#model IEnumerable<DKMPPIB.Presentation.ViewModelKlasor.VarlikKlasoru.ProjectActivityFinancialReportViewModel>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Region)
</th>
<th>
#Html.DisplayNameFor(model => model.City)
</th>
<th>
#Html.DisplayNameFor(model => model.ProjectName)
</th>
<th>
#Html.DisplayNameFor(model => model.FieldName)
</th>
<th>
#Html.DisplayNameFor(model => model.ProjectActivityName)
</th>
<th></th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Region)
</td>
<td>
#Html.DisplayFor(modelItem => item.City)
</td>
<td>
#Html.DisplayFor(modelItem => item.ProjectName)
</td>
<td>
#Html.DisplayFor(modelItem => item.FieldName)
</td>
<td>
#Html.DisplayFor(modelItem => item.ProjectActivityName)
</td>
<td>
<a onclick="readTender()" >
<img src='#Url.Content("~/Content/Images/glyphicons_free/glyphicons-342-briefcase.png")' />
</a>
</td>
<td>
<a href='#Url.Action("MyAction", "MyController")'>
<img src='#Url.Content("~/Content/Images/glyphicons_free/glyphicons-459-money.png")' />
</a>
</td>
#*Take attention to that line. I embed the ProjectActivityId here.*#
<td style="visibility:hidden" id="satirProjeFaaliyetId">#Html.DisplayFor(modelItem => item.ProjectActivityId)</td>
</tr>
}
</table>
<div id="tender-message" title="Tender Information" style="visibility:hidden">
<p>
<span class="ui-icon ui-icon-circle-check" style="float:left; margin:0 7px 50px 0;"></span>
Here is your tender detail:
</p>
<p>
Currently using <b>36% of your budget </b>.
</p>
</div>
<script type="text/javascript">
function readTender(){
//I will make an ajax call to get tender information. I need ProjectActivityId for this.
alert("read tender");
//var projectActivityId = $('#ProjectActivityId').find(":selected").val();
//console.log(bolgeDropdownId);
//$.ajax({
// type: "POST",
// url: '/Erp/GetTenderInformation',
// data: "{ProjectActivityId :'" + projectActivityId + "'}",
// contentType: "application/json; charset=utf-8",
// dataType: "json",
// success: successFunc,
// error: errorFunc
//});
}
</script>
As mentioned above, the javascript function readTender needs projectActivityId as an input to read tender information. I write projectActivityId to the last td tag of view. How can I pass projectActivityId to readTender()?
Here is the content of ProjectActivityFinancialReportViewModel:
public class ProjectActivityFinancialReportViewModel
{
private ProjectActivityLocationViewModel _projectActivityLocationVM;
private ProjectActivityViewModel _projectActivityVM;
[Display(Name = "Region")]
public string Region
{
get
{
if (this._projeFaaliyetKonumVM == null)
return string.Empty;
else
return this._projectActivityLocationVM.RegionName;
}
}
[Display(Name = "City")]
public string City
{
get
{
if (this._projectActivityLocationVM == null)
return string.Empty;
else
return this._projectActivityLocationVM.CityName;
}
}
[Display(Name = "Field Name")]
public string FieldName
{
get
{
if (this._projectActivityLocationVM == null || this._projectActivityLocationVM.LocationVm != null)
return string.Empty;
else
return this._projectActivityLocationVM.LocationVm.Name;
}
}
[Display(Name = "Project Activity Name")]
public string ProjectActivityName
{
get
{
if (this._projectActivityVM == null)
return string.Empty;
else
return this._projectActivityVM.ActivityVM.Name;
}
}
[Display(Name = "Project Name")]
public string ProjectName
{
get
{
if (this._projectActivityVM == null)
return string.Empty;
else
return this._projectActivityVM.ProjectVM.Name;
}
}
public int ProjectActivityId
{
get
{
if (this._projectActivityVM == null || this._projectActivityVM.Id == null)
return int.MinValue;
else
{
int id = this._projectActivityVM.Id ?? int.MinValue;
return id;
}
}
}
public TenderViewModel TenderVM
{
get
{
if (this._projectActivityVM == null)
return null;
else
return this._projectActivityVM.TenderVM;
}
}
public ProjeFaaliyetMaliRaporveProjeFaaliyetViewModel()
{
this._projectActivityLocationVM = null;
this._projectActivityVM = null;
}
}
You can handle click event for each row.
I suppose "selection" is handled by "click" over the row.
You can do that in this way:
Change your javascript function:
function readTender(projectActivityId) {
...
}
Change your tr inside the foreach:
<tr onclick="javascript:readTender(#item.ProjectActivityId)">;
...
<tr>
<td style="visibility:hidden" id="satirProjeFaaliyetId">#Html.DisplayFor(modelItem => item.ProjectActivityId)</td>
Problem here is, that you try to find an element by an id that is not present:
$('#ProjectActivityId').find(":selected").val();
So change the top line to the following:
<td style="visibility:hidden;" id="ProjectActivityId">#item.ProjectActivityId</td>
and the line in your js-code to
$('#ProjectActivityId').val();

How to create partial view via AJAX call

I am in learning phase and I want to create partial view from Ajax call. But for every click the page gets redirected to a altogether New Page. Below is my attempt.
Link I referred from Stack Overflow SO LINK
Model
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
Home Controller:
public ActionResult PartialViewContainer()
{
return View();
}
public PartialViewResult All()
{
var students = _context.Students.ToList();
return PartialView("_Student", students);
}
public PartialViewResult Top3()
{
var students = _context.Students.OrderByDescending(s => s.Age).Take(3);
return PartialView("_Student", students);
}
public PartialViewResult Bottom3()
{
var students = _context.Students.OrderBy(s => s.Age).Take(3);
return PartialView("_Student", students);
}
Main View located inside Home Folder
#{
ViewBag.Title = "PartialViewContainer";
}
<div style="font-family: Arial">
<h2>Students</h2>
#Html.ActionLink("All", "All", new AjaxOptions {
HttpMethod = "GET",
UpdateTargetId = "divStudents",
InsertionMode = InsertionMode.Replace
})
<span style="color:Blue">|</span>
#Html.ActionLink("Top3", "Top3", new AjaxOptions{
HttpMethod = "GET",
UpdateTargetId = "divStudents",
InsertionMode = InsertionMode.Replace
})
<span style="color:Blue">|</span>
#Html.ActionLink("Bottom", "Bottom3", new AjaxOptions{
HttpMethod = "GET",
UpdateTargetId = "divStudents",
InsertionMode = InsertionMode.Replace
})
<div id="divStudents"></div>
</div>
"_Student" Partial view located inside "Shared" folder
#model IEnumerable<WebApplication3.Models.Student>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table" style="border: 1px solid black; background-color: silver">
<tr>
<th>
#Html.DisplayNameFor(model => model.Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Age)
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#Html.DisplayFor(modelItem => item.Age)
</td>
</tr>
}
</table>
Initial page:
After Ajax Call
P.S: I have included jquery plug in.
But I could not find jquery.unobstrusice-ajax.js in my ASP.Net MVC
5 project template, so I have not included it.
Please guide me what am I doing wrong here.
EDIT 1
Replaced #html.ActionLink with #Ajax.ActionLink, but still it's
getting redirected to a new page.
try this:
Replace #html.ActionLink with #Ajax.ActionLink
#Ajax.ActionLink("All", "All", new AjaxOptions {
HttpMethod = "GET",
UpdateTargetId = "divStudents",
InsertionMode = InsertionMode.Replace
})
Keep in mind. AJAX CANNOT change the page.
I personally steered away from the unobtrusive ajax framwork. I just used good ole AJAX
What is happening is that ajax is not actually working and it is actually just doing an html GET.
Invoke a function like this when you press a button. This is how I solved the similar problem that I had.
This code may not be a direct cut and paste, but it is pretty close.
function CallAjax(actionPath) {
$.ajax({
url: actionPath,
type: 'POST',
success: function (partialView) {
$("#sampleContainer").html(partialView);
},
error: function () {
alert('error');
}
});
}

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