I want to show Course Code after selecting a department from drop down.
it searches from database and get but does not show at browser. Here is the drop down:
<select name="Id" id="Id">
<option value="">Select Department</option>
#foreach (var departments in ViewBag.ShowDepartments)
{
<option value="#departments.Id">#departments.Name</option>
}
</select>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script>
$(document).ready(function() {
$("#Id").change(function() {
var departmentId = $("#Id").val();
var json = { departmentId: departmentId };
$.ajax({
type: "POST",
url: '#Url.Action("ViewAllScheduleByDept", "ClassSchedule")',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(json),
success: function (data) {
//$("#myTable").append('<tr><th>ID</th><th>Name</th></tr>');
$('#Code').val(data.Code);
//$('#ContactNo').val(data.ContactNo);
//$('#Type').val(data.Type);
}
});
});
});
</script>
I am using mvc.
Your code should work fine as long as ViewAllScheduleByDept action method returns a json structure with a Code property.
[HttpPost]
public ActionResult ViewAllScheduleByDept(int departmentId)
{
//values hardcoded for demo. you may replace it value from db table(s)
return Json( new { Code="HardcodedValue", ContactNo="12345"} );
}
and you have an input form element with Id property value as Code in your page
<input type="text" id="Code" />
and you do not have any other script errors which is preventing your js code to execute.
Also, since you are sending just the Id value, you don't really need to use JSON.stringify method and no need to specify contentType property value.
$("#Id").change(function () {
$.ajax({
type: "POST",
url: '#Url.Action("ViewAllScheduleByDept", "ClassSchedule")',
data: { departmentId: $("#Id").val() },
success: function (data) {
alert(data.Code);
$('#Code').val(data.Code);
}
,error:function(a, b, c) {
alert("Error" + c);
}
});
});
use last before append
$("#myTable").last().append("<tr><td>ID</td></tr><tr><td>Name</td></tr>");
please see the link for details
Add table row in jQuery
Related
I'm having some issues with updating a partial view in my index view. Basically, based on a click, I would like to have updated information.
//controller
public ActionResult Index()
{
var filteredObservations = getFilteredObservationSessions().ToList();
var observationManagementVm = new ObservationManagementVM(filteredObservations);
return View(observationManagementVm);
}
public ActionResult indexPagedSummaries(int? page, List<ObservationSessionModel> data)
{
var alreadyFilteredObservations = data;
int PageSize = 10;
int PageNumber = (page ?? 1);
return PartialView(alreadyFilteredObservations.ToPagedList(PageNumber, PageSize));
}
My main view
//index.cshtml
#model AF.Web.ViewModels.ObservationManagementVM
....
<div id="testsim">
#Html.Action("indexPagedSummaries", new { data = Model.ObservationSessions })
</div>
<input id="new-view" value="Sessions" type="button" />
<script>
$("#new-view").click(function() {
$.ajax({
type: "GET",
data: { data: "#Model.FeedBackSessions" },
url: '#Url.Action("indexPagedSummaries")',
cache: false,
async: true,
success: function (result) {
console.log(result);
$('#testsim').html(result);
$('#testsim').show();
}
});
});
</script>
....
And my partial view
//indexPagedSummaries.cshtml
#model PagedList.IPagedList<AF.Services.Observations.ObservationSessionModel>
#using (Html.BeginForm("indexPagedSummaries"))
{
<ol class="vList vList_md js-filterItems">
#foreach (var item in Model)
{
#Html.DisplayFor(modelItem => item)
}
</ol>
<div>
Page #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber) of #Model.PageCount
#Html.PagedListPager(Model, page => Url.Action("Index",
new { page }))
</div>
}
Html.Action() returns what I want perfectly, but it doesn't seem to be able to be triggered by a button click.
So, I'm not getting any errors, but the url doesn't give any data back. When I try to run the Observation/indexPagedSummary url without passing in data, I get a System.ArgumentNullException error, so I'm assuming that something is being transferred to the view model. Any help would be so appreciated.
Have not run your code but I believe it is because you are not sending the data along with the #Url.Action
Main View:
//index.cshtml
#model AF.Web.ViewModels.ObservationManagementVM
....
<div id="testsim">
#Html.Action("indexPagedSummaries", new { data = Model.ObservationSessions })
</div>
<input id="new-view" value="Sessions" type="button" />
<script>
$("#new-view").click(function() {
$.ajax({
type: "GET",
data: { data: "#Model.FeedBackSessions" },
url: '#Url.Action("indexPagedSummaries", "[Controller Name]", new { data = Model.ObservationSessions})',
cache: false,
async: true,
success: function (result) {
console.log(result);
$('#testsim').html(result);
$('#testsim').show();
}
});
});
</script>
If that doesn't help I have had issues when I have had a content-type mismatch or a datatype mismatch. You may need to add those to you ajax request.
Change your ajax data line to this:
data: { data: JSON.stringify(#Model.FeedBackSessions) },
You may also need to add these lines to the ajax:
dataType: 'json',
contentType: 'application/json; charset=utf-8',
You can see in one of your comments above that the current URL is being formed with a description of the List Object, rather than the contents of it:
http://localhost:60985/Observation/indexPagedSummaries?data=System.Collections.Generic.List%601%5BAF.Services.Observations.ObservationSessionModel%5D&data=System.Collections.Generic.List%601%5BAF.Services.Observations.ObservationSessionModel%5D&_=1482453264080
I'm not sure if there's a better way, but you may even have to manually get the model data into Javascript before posting it.
eg:
<script>
var temp = [];
#foreach (var item in Model.FeedBackSessions){
#:temp.push(#item);
}
</script>
and then data: { data: JSON.stringify(temp) },
I'm new to AJAX, and I don't understand, why my data was not sent to controller.
So, on my View I have two input forms and a button:
HTML:
<input type="text" name="AddName">
<input type="text" name="AddEmail">
<button class="btn btn-mini btn-primary" type="button" name="add_btn" onclick="DbAdd()">Add</button>
I need after button "add_btn" clicked take data from these two inputs and send them to controller.
JavaScript:
<script type="text/javascript">
function DbAdd()
{
// Get some values from elements on the page:
var $form = $(this),
addedName = $form.find("input[name='AddName']").val(),
addedEmail = $form.find("input[name='AddEmail']").val();
$("#UserTable").html("<div>Please Wait...</div>");
$.ajax(
{
type: "POST",
url: "Save",
data:
{
name: addedName, email: addedEmail,
},
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: OnError
});
}
And this is my controller's method "Save" (I need to save data got from ajax to my DB):
[HttpPost]
public ActionResult Save(User userinfo)
{
string message = "";
using (var uc = new UserContext())
{
uc.UserList.Add(userinfo);
uc.SaveChanges();
message = "Successfully Saved!";
}
if (Request.IsAjaxRequest())
{
return new JsonResult { Data = message };
}
else
{
ViewBag.Message = message;
return View(userinfo);
}
}
The problem is that when I put a break point to my controller's method, I don't receive data from ajax, null's only. So I add an empty record to DB.
Any suggestions?
Looks like $form.find("input[name='AddName']").val() and $form.find("input[name='AddEmail']").val() both return null. You should use $("input[name='AddName']").val() and $("input[name='AddEmail']").val() instead. Change the definition of DbAdd() to below
<script type="text/javascript">
function DbAdd()
{
// Get some values from elements on the page:
var addedName = $("input[name='AddName']").val(),
addedEmail = $("input[name='AddEmail']").val();
var user = { Name: addedName, Email: addedEmail };
$("#UserTable").html("<div>Please Wait...</div>");
$.ajax(
{
type: "POST",
url: "Save",
data: JSON.stringify({ userinfo: user }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: OnSuccess,
error: OnError
});
}
</script>
There is an extra comma which may be causing syntax error:
data:
{
name: addedName, email: addedEmail, //<------------ here
}
and pass data like this:
var userinfo = { name: addedName, email: addedEmail };
data: JSON.stringify(userinfo)
Also you should see : Posting JavaScript objects with Ajax and ASP.NET MVC
I have a cshtml as follow,
DoPost.cshtml
#using (Html.BeginForm("Purchase", "PurchaseOrder", FormMethod.Post, new { #id = "frmPurchase" }))
{
// statements
// statements
<input type="button" id="submitPurchase" onclick = "myPurchase()" value="Select" />
}
In Javascript I have an array strings in variable "ExtraItems"
ExtraItems[0] ="123"
ExtraItems[1] ="124"
ExtraItems[2] ="125"
My Action which accept the data is as follows,
public ActionResult Purchase(PurchaseOrderModel model)
{
//Do some stuff with the passed data
return View("Purchase", model);
}
In the above PurchaseOrderModel, I have the property
public string[] SelectedProducts { get; set; }
to accept the Javascript Array elements.
What I tried:
The simple post did not work as the JavaScript array elements are not part of the Form elements,I couldn't use a #Html.HiddenFor because it is an array.
Hence tried to do an Ajax post under function myPurchase(),
$a.post('#Url.Action("Purchase", "PurchaseOrder")', { SelectedProducts: ExtraItems });
Here I did not get the ExtraItems details under model.SelectedProducts in the action. The biggest issue was i wanted to load the Purchase.cshtml View from the action, instead I got the controll back to the Jquery Post.
Please help me how can I solve this.
You should post your javascript array as a json object. You use the JSON.stringify() method converts a value to JSON. Something like :
$.ajax({
url: '#Url.Action("Purchase", "PurchaseOrder")',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
SelectedProducts: ExtraItems
})
});
Here is my example for solving your issue
-----------------------------------------
//Script
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<script>
var ExtraItems = ["aa","bb","cc","ff"];
function a()
{
$.ajax( {
type: 'POST',
url: '/Default1/Index',
data: { SelectedProducts: ExtraItems },
traditional: true,
success: function ( response )
{
alert( 'Sucs' );
}
} );
}
</script>
<button onclick="a();">click</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
//Controller
[HttpPost]
public ActionResult Index( string[] SelectedProducts )
{
return View();
}
Take a string property in your model and then send the data as comma separated string
var dataToSent = ExtraItems.join(',')
If you have a property named Datum of type string in your model Purchase then the data to be sent will be, passing model
data : 'Datum=' + dataToSent
In your action you can split data into array
also for return response you have to redirect the page in the success function of your ajax call
$.ajax( {
type: 'POST',
url: '/Default1/Index',
data: { SelectedProducts: ExtraItems },
traditional: true,
success: function ( response )
{
window.location.href = "/controller/action" <--your url
}
} );
Use $.ajax function with the option traditional:true for enabling ASP.NET MVC default model binding for the list of string items.
I want to display data in a table based on the search criteria in a textbox. I have implemented it without using Ajax but do not know how to call controller method using jquery and update table data. Please try to solve my problem. Thanks...
Index.cshtml
#model IEnumerable<MvcApplication4.Models.tbl_product>
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<script src="#Url.Content("~/Scripts/jquery-1.5.1.js")" type="text/javascript"></script>
<title>Index</title>
<script type="text/javascript">
$(document).ready(function () {
$('#Button1').click(function () {
alert("button clicked");
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home/Index',
data: "{'searchString':'" + document.getElementById('searchString').value + "'}",
async: false,
Success: function (response) {
alert("Success");
window.location.reload();
},
error: function () { alert("error"); }
});
});
});
</script>
</head>
<body>
#* #using (#Html.BeginForm("Index", "Home"))
{*#
#Html.TextBox("searchString");
<input type="button" value="filter" id="Button1" />
#* }*#
<table id="showData">
#{Html.RenderPartial("SearchList");}
</table>
</body>
</html>
SearchList.cshtml(Partial View)
#foreach (var item in Model)
{
<tr>
<td>#item.ProductName</td>
<td>#item.ProductId</td>
<td>#item.ProductDesc</td>
</tr>
}
HomeController.cs
public class HomeController : Controller
{
//
// GET: /Home/
ProductEntities dbentity = new ProductEntities();
public ActionResult Index()
{
return View(dbentity.tbl_product.ToList());
}
[HttpPost]
public ActionResult Index(string searchString)
{
var query = dbentity.tbl_product.Where(c => c.ProductName.Contains(searchString));
return View(query.ToList());
}
}
$.ajax({
url: '/ControllerName/ActionName',
type: "POST",
data: {criteria: 'criteria'},
contentType: "application/json",
success: function (data) {
//Replace existing table with the new view (with the table).
}
});
//write ControllerName without the key controller.
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'Home/Index',
data: JSON.stringify({'searchString':document.getElementById('searchString').value }),
async: false,
Success: function (response) {
alert("Success");
//append the data in between table tbody like,
$('table tbody').html(response);
//No window.location.reload(); It will cause page reload initial data will appear in grid.
},
error: function () { alert("error"); }
});
return false
Hope this helps.
Your ajax request should look like:
$.ajax({
url: '/<ControllerName>/<MethodName>',
type: "POST",
data: requestData,
contentType: "application/json;charset=utf-8",
success: function (data, textStatus, XMLHTTPRequest) {
//Success callback handling
},
error: function (XMLHTTPRequest, textStatus, errorThrown) {
//Error callback handling
},
cache: false //whether you want to cache the response or not.
});
I'm not going to give you the exact answer, but to help you to get it.
There are two steps:
First you must get sure the request is being done, and the response is being get on the browser.
To do so, you can
do it on your way: leave only the alert("Success"); and check it's being run.
better than that, open the browser's developer console (I prefer Chrome, but you can also use IE or FireFox + FireBug add-on) using F12. Set breakpoints and inspect variable values and code flow. See thit tutorial for Chrome developer tools.
set a breakpoint on the server action, and check it's executed
Second Once you're sure the firs part is working fine, use your succes function to replace the table content with the data received in the response. You can do it in several ways with jQuery. For example
$('#showData').html(response);
Again, you can execute this code and inspect the contents of response from the developer's console in your browser. This makes things eaiser when you're starting to use javascript.
(If your action generated the whole table, you could use jQuery's replaceWith which replaces the target, instead of its content. Don't use this for this case).
FINAL NOTE: please, remove this code window.location.reload();!!! This reloads the whole page with the current URL, so whatever thing you do in advance will be lost.
I need some help. I write little app using ASP.NET MVC4 with JavaScript and Knockout and I can't send data from javascript to MVC Controller and conversely. For example, the part of JS looks like that:
JavaScript
self.Employer = ko.observable();
self.AboutEmployer = function (id) {
$.ajax({
Url.Action("GetEmployer", "Home")
cache: false,
type: 'GET',
data: "{id:" + id + "}",
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
self.Employer(data);
}
}).fail(
function () {
alert("Fail");
});
};
In ASP.NET MVC Home Controller I'm getting employer by ID and return it as Json:
C#
public JsonResult GetEmployer(int id)
{
var employer = unit.Repository<Employer>().GetByID(id);
return Json(employer, JsonRequestBehavior.AllowGet);
}
My View return another Controller (Home/KnockOutView). My View also gets another objects and depending what recieve, has different look:
HTML
...
<b>About Company: </b><a href="#" data-bind="click: $root.AboutEmployer.bind($data, Vacancy().EmployerID)">
<span data-bind=" text: Vacancy().Employer"></span></a>
<div data-bind="if: Vacancy">
<div id="VacancyDescription"><span data-bind="text:DescriptionShort"></span>
</div>
</div>
<div data-bind="if: Employer">
<div data-bind="text: Employer().EmployerDescription"></div>
</div>
Everything works great, I receive Vacancy and Employer objects in JS and show it in HTML using Knockout, but my URL all time still the same!!! But I want to change URL all time, when i'm getting Vacancy or Employer.
For example, if I want to get Employer, using method GetEmployer, URL should looks like that: ~/Home/GetEmployer?id=3
If I change this string of Code
Url.Action("GetEmployer", "Home") at url: window.location.href = "/home/GetEmployer?id=" + id URL will be changed, but Controller returns me an Json object and shows it in window in Json format.
Help me, please, to change URL and get information in Controller from URL.
Thanks.
Try below code, hope helps you
This code works %100 , please change below textbox according to your scenario
HTML
<input type="text" id="UserName" name="UserName" />
<input type="button" onclick="MyFunction()"value="Send" />
<div id="UpdateDiv"></div>
Javascript:
function MyFunction() {
var data= {
UserName: $('#UserName').val(),
};
$.ajax({
url: "/Home/GetEmployer",
type: "POST",
dataType: "json",
data: JSON.stringify(data),
success: function (mydata) {
$("#UpdateDiv").html(mydata);
history.pushState('', 'New URL: '+href, href); // This Code lets you to change url howyouwant
});
return false;
}
}
Controller:
public JsonResult GetEmployer(string UserName)
{
var employer = unit.Repository<Employer>().GetByID(id);
return Json(employer, JsonRequestBehavior.AllowGet);
}
Here is my controller action.
[HttpPost]
public ActionResult ActionName(string x, string y)
{
//do whatever
//return sth :)
}
and my post action is here.
<script type="text/javascript">
function BayiyeCariEkle(){
var sth= $(#itemID).text();
var sth2= $(#itemID2).text();
$.post("/ControllerName/ActionName", { x: sth, y: sth2});
}
</script>
use data parameters like this {id:id, otherPara:otherParaValue}
$.ajax({
url:Url.Action("GetEmployer", "Home")
type: 'GET',
data: {id:id},
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
alert(data)
}
});
Due to MVC being slightly annoying in it's processing of routes to the same view, I've had success doing this:
self.Employer = ko.observable();
self.AboutEmployer = function (id) {
$.ajax({
url: "#Url.Action("GetEmployer", "Home", new { id = "PLACEHOLDER"})".replace("PLACEHOLDER", id),
cache: false,
type: 'GET',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
self.Employer(data);
}
}).fail(
function () {
alert("Fail");
});
};
You can use standard url: "#Url.Action("GetEmployer", "Home")/" + id, but on refresh, the route with the existing ID stays in subsequent calls, so it begins appending the id, which obviously doesn't work. By specifying the ID in call, that behavior is no longer present.
The best way for navigation on my opinion, is to use sammy.js. Here is a post about that kazimanzurrashid.com