Display all the models using API and MVC4 - c#

I created a API application where I can perform the crud operations. However, I am unable to display all the models in my cshtml.
I have created my API controller, which has the getAllUsers methods and in my home controller, I just call the Index View. In my view, I have a script which calls the getAllUsers methods. Below is my code:
API controller:
namespace WebApiQues.Controllers
{
public class UserController : ApiController
{
private WebApiQuesEntities db = new WebApiQuesEntities();
//Get all users
public IEnumerable<User> GetAllUsers()
{
var UserList = from s in db.Users
orderby s.Id
select s;
return UserList;
}
}
Controller:
public class HomeController : Controller
{
//
// GET: /Home/
public UserController userController = new UserController();
public ActionResult Index()
{
//var UserList = userController.GetAllUsers();
//ViewBag.UserList = UserList;
return View();
}
}
Index.cshtml:
#{
ViewBag.Title = "Index";
}
#model IEnumerable<WebApiQues.Models.User>
<div>
<div>
<h2>All Products</h2>
<ul id="products" />
</div>
</div>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
var uri = 'api/user/getallusers';
$(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (data) {
// Add a list item for the product.
$('<li>').appendTo($('#products'));
});
});
});
</script>
I believe the problem comes from the script in cshtml but I can't find where I am doing it wrong. Any idea?
EDITED:
If I add a console.log(data), I can see that data has the list of users.

try this:
add your jquery script to the scripts section:
#section scripts
{
<script type="text/javascript">
$(function() {
var uri = 'api/user/getallusers';
$.getJSON(uri, function(data) {
$.each(data, function(index, v) {
$('#products').append('<li>'+v.PropertyName+'</li>');
//Change property name to the property of your object
});
});
});
</script>
}
$.each expects two arguments in the callback function: the index of your array and the actual data object itself:
callback Type: Function( Integer indexInArray, Object value ) The
function that will be executed on every object.
http://api.jquery.com/jquery.each/

Assuming User has 'Name' property, try this code
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
$.each(data, function (data) {
// Add a list item for the product.
$('#products').append('<li>'+data.Name+'</li>');
});
});

Related

api service not getting called in syncfusion Schedule widget asp.net boiler plates

I want to show some data in syncfusion Schedule widget between range of specific dates But I am unable to get any type of data in syncfusion Schedule widget. I want to call Api Using jQuery. My Api is not getting called even I have tried to show some hard coded data but I am getting nothing in
syncfusion Schedule widget.
here is my view code.
`
#{
ViewBag.CurrentPageName = AppPageNames.Common.DayReportView;
}
#section Scripts
{
<environment names="Development">
<script src="/view-resources/Areas/App/Views/POSConfigurations/DayReportView/Index.js" asp-append-version="true"></script>
</environment>
<environment names="Staging,Production">
<script src="/view-resources/Areas/App/Views/POSConfigurations/DayReportView/Index.min.js" asp-append-version="true"></script>
</environment>
}
<div class="content d-flex flex-column flex-column-fluid" id="kt_content">
<abp-page-subheader title="#L("DayReportView")">
</abp-page-subheader>
<ejs-schedule id="schedule" , height="700px">
</ejs-schedule>
</div>`
here is my index.js file code
(function () {
$(function () {
var _GetShortOvertimeService = abp.services.app.DayReport;
$(function () {
var dataManager = ej.DataManager({
// get the required appointments from Web API service
url: "_GetShortOvertimeService.GetShortOverFromDayReport",
// enable cross domain
crossDomain: true
});
$("#schedule").ejSchedule({
currentDate: new Date(2022, 6, 22),
appointmentSettings: {
// Configure the dataSource with dataManager object
dataSource: dataManager
}
});
});
});
Here is Api that i want to call
public class DayReportAppService : myAppServiceBase, IDayReportAppService
{
private readonly IDayReportRepository _dayReportRepository;
public DayReportAppService(IDayReportRepository dayReportRepository){
_dayReportRepository = dayReportRepository;
}
public async Task<decimal> GetShortOverFromDayReport(Guid? posId, DateTime? startDate, DateTime? endDate)
{
var shorOver = await _dayReportRepository.GetShortOverFromDayReportSP(posId, startDate, endDate);
return shorOver;
}
}
here is my controller code
public class DayReportViewController : myappControllerBase
{
public IActionResult Index()
{
return View();
}
}
}
here is my frontend view

Asp.Net load data by button click

I have a simple list view where I'm loading my data.
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Your application description page.";
IList<Product> products;
using (ISession session = NHibernateSession.OpenSession()) // Open a session to conect to the database
{
products = session.Query<Product>().ToList(); // Querying to get all the books
}
return View(products);
}
}
View is a simple list view from template.
Now, I need to load data to list view just after button click.
So as I understand I need to render partial view.
I've add this to view:
<button id="Load">Load data</button>
<script type="text/javascript">
var url = '#Url.Action("LoadData", "Home")';
$('#Load').click(function() {
var keyWord = $('#Keyword').val();
$('#result').load(url);
})
</script>
<div id="result"></div>
And add controller action:
public ActionResult LoadData()
{
// here will be model creation and passing view
return PartialView();
}
But controller action doesn't get called.
What should I do?
This is now I would do it.
We create an action method which return JSON on http gets
public class SomeController : Controller
[HttpGet]
public ActionResult LoadData()
{
using (ISession session = NHibernateSession.OpenSession()) // Open a session to conect to the database
{
products = session.Query<Product>().ToList(); // Querying to get all the books
}
return Json(new {data=product},
JsonRequestBehavior.AllowGet);
}
Inside your view we do a ajax request to get the data by calling LoadData
$.ajax({
type: 'get',
dataType: 'json',
url: 'SomeController/LoadData',
success: function (data) {
//Render data to view maybe using jquery etc
},
error: function(data) {
//Notify user of error
}
});
Hope this helps man

ASP.Net MVC + Autocomplete Search not working

I'm a beginner & I'm trying to develop a autocomplete search box with ASP.Net MVC 5. I use Northwind Database and Entity Framework 6.
Here is my index.cshtml code
#model IEnumerable<AutoComplete3.Models.Customers>
<link href="~/Content/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="~/Scripts/jquery-1.9.1.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-ui.js"></script>
<script type="text/javascript">
$(function () {
$("#txtSearch").autocomplete({
source: '#Url.Action("GetCustomers")'
});
});
</script>
#using (#Html.BeginForm())
{
<b>Name : </b>
#Html.TextBox("searchTerm", null, new { #id = "txtSearch" })
<input type="submit" value="Search" />
}
Here is my CustomerController class
public class CustomersController : Controller
{
northwindEntities db = new northwindEntities();
public ActionResult Index()
{
return View(db.Customers);
}
[HttpPost]
public ActionResult Index(string SearchTerm)
{
List<Customers> customers;
if (string.IsNullOrEmpty(SearchTerm))
{
customers = db.Customers.ToList();
}
else
{
customers = db.Customers.Where(c => c.CompanyName.StartsWith(SearchTerm)).ToList();
}
return View(customers);
}
public JsonResult GetCustomers(string term)
{
List<string> customers;
customers = db.Customers.Where(c => c.CompanyName.StartsWith(term)).Select(y => y.CompanyName).ToList();
return Json(customers,JsonRequestBehavior.AllowGet);
}
}
This code is working when i am searching records, by entering keyword & clicking submit button. But the GetCustomer method cannot be called by the jquery script. Inspect Elements shows following error.
Uncaught TypeError: $(...).autocomplete is not a function
The text box should be suggest Company Names to the textbox itself. How to correct this.
Thanks.
Javascript
$(document).ready(function () {
$("#txtSearch").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("GetCustomers","Home")',
type: "POST",
dataType: "json",
data: { searchTerm: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.CompanyName, value: item.CompanyName };
}))
}
})
},
messages: {
noResults: "", results: ""
},
});
})
View
#using (#Html.BeginForm())
{
<b>Name : </b>
#Html.TextBox("searchTerm", null, new { #id = "txtSearch" })
<input type="submit" value="Search" />
}
Controller
Please update your controller with [HttpPost]
[HttpPost]
public JsonResult GetCustomers(string searchTerm)
{
List<string> customers;
customers = db.Customers.Where(c => c.CompanyName.StartsWith(term)).Select(y => y.CompanyName).ToList();
return Json(customers,JsonRequestBehavior.AllowGet);
}

How to update partial view from another partial view via action results

I have three partial views on main view
on the first partial view I have search functionality and when user clicks on search I want to refresh results into 3rd partial view.
Controller:
public ActionResult Search()
{
virtualmodel vm = new virtualmodel();
return PartialView(svm);
}
[HttpPost]
public ActionResult Search(ViewModel svm)
{
// Query to retrive the result
// I am not sure what to return from here. Link to another action or just return back to same same partial
}
public ActionResult AnotherPartialPartial()
{
}
In main view
#{Html.RenderAction("Search", "Searchc");
}
How to do it? Do I need ajax?
Using ajax you can call a controller action and return it's response to a particular div.
Empty div:
<div class="row" id="div3">
</div>
Ajax to display html in empty div:
function performSearch(searchCriteria) {
//get information to pass to controller
var searchInformation = JSON.stringify(**your search information**);
$.ajax({
url: '#Url.Action("Search", "ControllerName")',//controller name and action
type: 'POST',
data: { 'svm': searchInformation } //information for search
})
.success(function (result) {
$('#div3').html(result); //write returned partial view to empty div
})
.error(function (xhr, status) {
alert(status);
})
}
jQuery will help you with it!
Try to handle submit button onclick event like this:
$("#yourButtonId").click(function()
{
$.ajax({
type: "POST",
url: "/yourUrl", //in asp.net mvc using ActionResult
data: data,
dataType: 'html',
success: function (result) {
//Your result is here
$("#yourContainerId").html(result);
}
});
});
You can do it with ajax.
First, change your html.beginform to ajax.beginform in your view and add div id into UpdateTargetId that you want to change contents. After updating first partial with ajax.beginform, you can update other partialviews with ajax.beginform's "OnSuccess" function. You have to add update function like that:
#using (Ajax.BeginForm("YourAction", "YourController",
new { /*your objects*/ }, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ChangeThisPart", OnSuccess = "OnSuccessMethod" }))
{
/*your code*/
}
<script>
function OnSuccessMethod() {
$("#YouWantToChangeSecondDivID").load('/YourController/YourAction2');
$("#YouWantToChangeThirdDivID").load('/YourController/YourAction3');
};
</script>
Then in your controller, return a partial view to refresh your view part that you entered it's ID in UpdateTargetId value:
public ActionResult YourControllerName(YourModelType model)
{
...//your code
return PartialView("_YourPartialViewName", YourViewModel);
}
Note: Don't forget to add reference to "jquery.unobtrusive-ajax.min.js" in your view while using ajax.
So, say you have your View with PartialView, which have to be updated by button click:
<div class="target">
#{ Html.RenderAction("UpdatePoints");}
</div>
<input class="button" value="update" />
There are some ways to do it. For example you may use jQuery:
<script type="text/javascript">
$(function(){
$('.button')click(function(){
$.post('#Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
$('.traget').Load('/Home/UpdatePoints');
})
});
});
</script>
PostActionToUpdatePoints is your Action with [HttpPost] attribute, which you use to update points
If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:
[HttpPost]
public ActionResult UpdatePoints()
{
ViewBag.points = _Repository.Points;
return PartialView("UpdatePoints");
}

jquery click method is not attached to button

I have asp.net mvc 5 application but I can't get this fairly simple script to work. I am new to this MVC (I am WebForms guy).
Basically jQuery is not attaching .click() event to the button to post data to the underlying controller.
Can somebody pinpoint what I am doing wrong?
The View (HelloWorld/Index.cshtml):
#model HelloWorld.Models.HelloWorldModel
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
<script src="~/Scripts/jquery-2.1.3.min.js"></script>
</head>
<body>
<div>
#using (Html.BeginForm("Welcome","HelloWorld",FormMethod.Post, new {id = "myhelloform"})){
<span>Name:</span>
#Html.TextBoxFor(model=> model.Name)
<button id="btnPost" type="button">Post</button>
}
</div>
<script>
var testform = function () {
var init = function () {
$("#btnPost").on("click", function () {
alert("anybody there??");
submitForm();
});
};
var submitForm = function () {
$.hit({
url: "#Url.Action("Welcome", "HelloWorld")",
data: $("#myhelloform").serializeArray(),
success: function (response) {
alert(response.Message);
}
});
};
return {
Init: init
};
};
</script>
</body>
</html>
</html>
The Controller (Controllers/HelloWorldController.cs):
using System.Web.Mvc;
namespace HelloWorld.Controllers
{
public class HelloWorldController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult Welcome()
{
return Json("test");
}
}
}
The Model (Models/HelloWorldModel.cs)
namespace HelloWorld.Models
{
public class HelloWorldModel
{
public string Name { get; set; }
}
}
Delete the variables testform and init and it works (Also need to use $( document ).ready as #Tbseven mentions):
$( document ).ready(function() {
$("#btnPost").on("click", function ()
{
alert("anybody there??");
});
});
Fiddle: https://dotnetfiddle.net/HCdFXM
You have to place your jquery code inside next function:
$( document ).ready(function() {
// Here
});
$( document ).ready(function() {
$("#btnPost").on("click", function () {
alert("anybody there??");
submitForm();
});
function submitForm () {
$.hit({
url: "#Url.Action("Welcome", "HelloWorld")",
data: $("#myhelloform").serializeArray(),
success: function (response) {
alert(response.Message);
});
};
});
You can use input instead of button and there is no need to add click event for that.
<input type="submit" id="btnPost" />

Categories

Resources