passing model from view to controller using jquery - asp.net-mvc-3

I have a view
#using staffInfoDetails.Models
#model staffInfo
<link href="../../Content/myOwn.css" rel="stylesheet" type="text/css" />
#{staffInfo stf = Model;
}
<div id="education1">
#using (Html.BeginForm("addNewEdu","Home",FormMethod.Post))
{
#Html.HiddenFor(x=>x.StaffId)
<table>
<tr>
<th>Country</th>
<th>Board</th>
<th>Level</th>
<th>PassedYear</th>
<th>Division</th>
</tr>
<tr>
#Html.EditorFor(x => x.eduList)
</tr>
<tr>
#*<td><input type="submit" value="create Another" id="addedu"/> </td>*#
#*<td>#Html.ActionLink("Add New", "addNewEdu", new { Model })</td>*#
</tr>
</table>
}
<button id="addedu">Add Another</button>
</div>
I want to pass the model staffInfo to controller using jquery as below
<script type="text/javascript">
$(document).ready(function () {
$("#addedu").live('click', function (e) {
// e.preventDefault();
$.ajax({
url: "Home/addNewEdu",
type: "Post",
data: { model: stf },//pass model
success: function (fk) {
// alert("value passed");
$("#education").html(fk);
}
});
});
});
</script>
the jquery seems to pass only elements not whole model so how can I pass model from the view to the controller so that I don't have to write the whole parameters list in jquery

u can give ID to the form by using this
#using (Html.BeginForm("addNewEdu", "Home", FormMethod.Post, new { id = "addNewEduForm" }))
{
}
Then in the script
<script type="text/javascript">
$('#addedu').click(function(e) {
e.preventDefault();
if (form.valid()) { //if you use validation
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: $("#addNewEduForm").serialize(),
success: function(data) {
}
});
}
});
</script>

As I can see you trying to submit form with AJAX? Look at serialize function.
$('#addedu').click(function(e) {
e.preventDefault();
var form = $('form');
if (form.valid()) { //if you use validation
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
success: function(r) {
}
});
}
});

You can get your values with getElementById then send your action:
$(document).ready(function () {
var select = document.getElementById('...');
$.ajax({
type: "get",
url: "get_street_name",
data: { a: select },
success: function (data) {
$('#result').html(data);
}
});
}

Related

How to call an action method upon selection from the <select> dropdwon in ASP.NET Core 6 MVC?

I created a dropdown using the <select> HTML element. Now I want to call an action after user makes a selection from the list.
<select name="ddAircraft" id="ddAircraft" class="form-control form-select-sm form-select"
asp-items="#(new SelectList(ViewBag.ddaircraft,"id","name"))">
</select>
I would also like to know if user enter a value in a input box. Then I want to run a Javascript method. How I can do that?
I tried to do onClick but I am getting usual error.
It would help if you could show the details of your error,
I Tried with the codes below:
#{
var sel = new List<SelectListItem>()
{
new SelectListItem(){Text="1",Value="1" },
new SelectListItem(){Text="2",Value="2" },
new SelectListItem(){Text="3",Value="3" }
};
}
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script>
$(function () {
$('#selectlist').change(function () {
window.location.href = "Privacy";
})
});
</script>
<script>
$(function () {
$('#input').change(function () {
window.location.href = "Privacy";
})
});
</script>
<input id="input" value=""></input>
<select id="selectlist" asp-items=sel></select>
The result:
To pass the selected item value ,you could try :
<script>
$(function () {
$('#selectlist').change(function () {
window.location.href = "Home/Privacy?sel=" + $(this).val();
})
});
</script>
The result:
if you want to make a post request, you could try with ajax as below:
<script>
$(function () {
$('#selectlist').change(function () {
var sel = $(this).val();
var input = document.getElementById("input").value;
$.ajax({
url: "Home/Test",
contentType: "application / json; charset = utf - 8",
type: "post",
data: JSON.stringify({
sel: sel,
input: input
}),
datatype: "json",
success: function (data) {
console.log(data);
}
})
})
});
</script>
The result:

DataTable with .Net5

I tried to use datatable with my project and I always got undefined when data return from the controller while I checked the controller already returned 1000 records
this is my controller
[HttpGet]
public JsonResult get_Student_Info()
{
var model = (from C in _db1.ClassesInfos
select new Classes
{
ClassId = C.Id,
ClassCounty = C.ClassCounty ?? "",
ClassLocation = C.ClassLocation,
ClassSize = C.ClassSize ?? 0,
ClassDate = C.ClassDate.ToString(),
//ClassMonitorId = C.MonitorId,
//ClassActive = C.Active ?? 0,
//ClassLastModifedDate = C.LastModifiedDate.ToString(),
//ClassPasscode = C.Passcode,
//ClassType = C.ClassType
}).FirstOrDefault();
return Json(mymodel, System.Web.Mvc.JsonRequestBehavior.AllowGet);
}
and this is my view
$(function () {
$.ajax({
type: "GET",
//url: "/Instructor/get_Student_Info",
url: '#Url.Action("get_Student_Info", "Instructor")',
mimeType: 'json',
async: true,
success: function(data) {
$.each(data, function (i, data) {
alert(data.ClassCounty);
alert(data.ClassLocation);
var body = "<tr>";
body += "<td>" + data.ClassCounty + "</td>";
body += "<td>" + data.ClassLocation + "</td>";
body += "</tr>";
$( "#ClasssInfo tbody" ).append(body);
});
/*DataTables instantiation.*/
$( "#ClasssInfo" ).DataTable();
},
});
});
In asp.net mvc, it should be:
Model:
public class Class
{
public string ClassCounty { get; set; }
public string ClassLocation { get; set; }
}
View:
<table id="ClasssInfo">
<thead>
<tr>
<th>ClassCounty</th>
<th>ClassLocation</th>
</tr>
</thead>
<tbody></tbody>
</table>
#section Scripts
{
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
$(function () {
$.ajax({
type: "GET",
url: "#Url.Action("get_Student_Info", "Home")",
mimeType: 'json',
async: true,
success: function (data) {
$("#ClasssInfo").DataTable({
data: data,
columns: [{ 'data': 'ClassCounty' },
{ 'data': 'ClassLocation' }]
});
},
});
});
</script>
}
Controller:
public JsonResult get_Student_Info()
{
//must be list model
var model = new List<Class>(){
new Class()
{
ClassCounty = "aa",
ClassLocation = "location"
}
};
return Json(model, JsonRequestBehavior.AllowGet);
}
In asp.net core/.net 5, it should be:
View:
Note: In asp.net core/.net 5, the response json format is camel case.
<table id="ClasssInfo">
<thead>
<tr>
<th>ClassCounty</th>
<th>ClassLocation</th>
</tr>
</thead>
<tbody></tbody>
</table>
#section Scripts
{
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
$(function () {
$.ajax({
type: "GET",
url: "#Url.Action("get_Student_Info", "Home")",
mimeType: 'json',
async: true,
success: function (data) {
$("#ClasssInfo").DataTable({
data: data,
columns: [{ 'data': 'classCounty' }, //difference here..should be camel case
{ 'data': 'classLocation' }]
});
},
});
});
</script>
}
Controller:
public JsonResult get_Student_Info()
{
var model = new List<Class>(){
new Class()
{
ClassCounty = "aa",
ClassLocation = "location"
}
};
return Json(model);
}

How to call simple ajax program in asp.net mvc

I start learning Ajax in asp.net MVC 4. I want to create a very simple program based on the following scenario.
I want two textboxes on a form (FirstName, LastName) and a button, Whenever i write something in these textboxes, these values should assign to two labels (lblFristName, lblLastName) by using Ajax. So that page will not refresh.
How can i achieve the above functionality?. Please provide clear/simple code examples and no other site links, Thanks.
Following is the code that iam trying for:-
#model MvcAppLearn.Models.Student
#{
ViewBag.Title = "AjaxCall";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>AjaxCall</h2>
#using (Html.BeginForm("AjaxCall", "Ajax", FormMethod.Post, new { id = "my-form" }))
{
#:FirstName #Html.EditorFor(x => x.FirstName);
#:FirstName #Html.EditorFor(x => x.LastName);
<input type="submit" value="Submit" />
}
<br />
<div id ="result">
</div>
#section scripts{
<script type="text/javascript">
$(function () {
$("#my-form").on("Submit", function (e) {
//e.preventDefault();
debugger
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
succes: function (data) {
$("#result").html(data);
},
error: function () {
alert("Oh noes");
}
});
});
});
</script>
}
Partial View
#model MvcAppLearn.Models.Student
#{
ViewBag.Title = "AjaxCall";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Ajax Partial View</h2>
<label>#Html.DisplayFor(item => item.FirstName)</label><br />
#Html.Label(Model.LastName)
#* #Html.EditorFor(x => x.FirstName)<br />
#Html.EditorFor(x => x.LastName)*#
Controller
public ActionResult AjaxCall()
{
return View();
}
[HttpPost]
public virtual ActionResult AjaxCall(Student model)
{
return PartialView("ajax_partial" , model);
}
So above code take me to the partial view, but i want to live on that page where my textboxes are placed and at the same page i want to display these labels. Please correct if there is any mistake, thanks
If this is something your view looks like,
#Html.TextBoxFor(r => r.textbox1, new { id = "textbox1"})
<label id="label1"></label>
You can achieve this using simple jquery change/keyup event
$('#textbox1').bind("change keyup", function() {
$('#label1').val($('#textbox1').val())
});
I have done it, Problem was i write "s" as capital in 'submit' and missed 's' in last at ":success" function. Following is the correct code.
<script type="text/javascript">
$(function () {
$("#my-form").on("submit", function (e) {
e.preventDefault();
//debugger
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (data) {
$("#result").html(data);
},
error: function () {
alert("Oh noes");
}
});
});
});
</script>

ng-grid in from tag with run at server in aspx page

i am calling the ajax function on click of button it returns the json data and i am passing the data to the main.js script file(controller) its getting the data and binding the data to the ng-grid, the question here is whne i put the ng-grid in the from tag it does not dispaly the data
<script type="text/javascript">
$(document).ready(function () {
$("#mybutton").click(function () {
var scope = angular.element(document.getElementById("wrap")).scope(); // to get access all the varibales defined in the contoller
scope.$apply(function () {
$.ajax({
type: "POST",
url: "Website/Nggrid.asmx/GetDataForNgGrid",
success: function (result) {
// console.log(result);
var fd = JSON.parse(result); //parsing the json string
scope.updateMessage(fd);
alert("hi");
},
error: function (xmlhttprequest, Status, thrownError) {
alert(thrownError.toString());
alert(thrownError);
}
});
});
});
});
</script>
this is the function i am calling when the user clicks on button
<body ng-controller="MyCtrl">
<%--<form id="form1" runat="server">--%>
<div id="wrap" class="gridStyle" ng-grid="gridOptions">
</div>
<button id="mybutton">
Try it</button>
<%-- </form>--%>
</body>
this is the main.js
var app = angular.module('myApp', ['ngGrid']);
app.controller('MyCtrl', function ($scope) {
$scope.myData = [];
$scope.updateMessage = function (_s) {
$scope.myData = _s;
// $scope.Enable = true;
};
$scope.gridOptions = {
data: 'myData',
columnDefs: [
{ field: 'Status', displayName: 'Status', width: "*" }
]
};
});
my question is here that when i put ng-grid in the from tag it wont show the data, please give the suggestion on this
<form id="form1" runat="server">
<div id="wrap" class="gridStyle" ng-grid="gridOptions">
</div>
<button id="mybutton">
Try it</button>
</form>

Passing Id from javascript to Controller in mvc3

How to pass Id from javascript to Controller action in mvc3 on ajax unobtrusive form submit
My script
<script type="text/javascript">
$(document).ready(function () {
$("#tblclick td[id]").each(function (i, elem) {
$(elem).click(function (e) {
var ID = this.id;
alert(ID);
// var url = '#Url.Action("Listpage2", "Home")';
var data = { Id: ID };
// $.post(url,data, function (result) {
// });
e.preventDefault();
$('form#myAjaxForm').submit();
});
});
});
</script>
the how to pass Id on using $('form#myAjaxForm').submit(); to controller
instead of
$.post(url,data, function (result) {
// });
My View
#using (Ajax.BeginForm("Listpage2", "", new AjaxOptions
{
UpdateTargetId = "showpage"
}, new { #id = "myAjaxForm" }))
{
<table id="tblclick">
#for (int i = 0; i < Model.names.Count; i++)
{
<tr>
<td id='#Model.names[i].Id'>
#Html.LabelFor(model => model.names[i].Name, Model.names[i].Name, new { #id = Model.names[i].Id })
<br />
</td>
</tr>
}
</table>
}
</td>
<td id="showpage">
</td>
I would avoid using the Ajax Beginform helper method and do some pure handwritten and Clean javascript like this
<table id="tblclick">
#foreach(var name in Model.names)
{
<tr>
<td id="#name.Id">
#Html.ActionLink(name.Name,"listpage","yourControllerName",
new { #id = name.Id },new { #class="ajaxShow"})
</td>
</tr>
}
</table>
<script>
$(function(){
$(".ajaxShow")click(function(e){
e.preventDefault();
$("#showpage").load($(this).attr("href"));
});
});
</script>
This will generate the markup of anchor tag in your for each loop like this.
<a href="/yourControllerName/listpage/12" class="ajaxShow" >John</a>
<a href="/yourControllerName/listpage/35" class="ajaxShow" >Mark</a>
And when user clicks on the link, it uses jQuery load function to load the response from thae listpage action method to the div with id showPage.
Assuming your listpage action method accepts an id parameter and returns something
I am not sure for $.post but I know window.location works great for me.
Use this instead and hopefully you have good results :)
window.location = "#(Url.Action("Listpage2", "Home"))" + "Id=" + ID;
replace $('form#myAjaxForm').submit(); with this code and nothing looks blatantly wrong with your jscript.
Just use a text box helper with html attribute ID.
#Html.TextBox("ID")
You can do this too:
var form = $('form#myAjaxForm');
$.ajax({
type: "post",
async: false,
url: form.attr("action"),
data: form.serialize(),
success: function (data) {
// do something if successful
}
});

Resources