How to call simple ajax program in asp.net mvc - ajax

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>

Related

ASP.NET MVC ViewBag values not being displayed in view after Ajax call

I have following view and controller code:
Index.cshtml
#using (Html.BeginForm("Create", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<span style="color:green; font-weight:bold;" id="Message">#ViewBag.Message</span>
<input type="text" id="txtMessage" />
<input type="submit" id="btnSubmit" value="Submit" />
}
<script src="~/Scripts/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$('#btnSubmit').click(function (event) {
$.ajax({
type: "POST",
url: "/Home/Create",
dataType: "json",
contentType: "application/json; charset=utf-8",
async: false,
data: JSON.stringify({
'message': $('#txtMessage').val()
})
});
});
</script>
Controller code:
public class HomeController : Controller
{
public ActionResult Index(string message)
{
return View();
}
[HttpPost]
public ActionResult Create(string message)
{
ViewBag.Message = message;
return View("Index");
}
}
After clicking the button and making ajax call I'm not able to see the message set in the Create method to ViewBag.Message inside the index view.
If you are using Begin form and button type as submit then why write ajax method?
Remove your btnSubmit click from javascript code and use textbox as TextBoxFor,
#Html.TextBoxFor(m => m.message, new { #class = "form-control" })
it should work.
Update Answer for without strongly type
As per code, you are using Begin Form so not required to ajax call.
So first remove javascript code or if you keep that code so no meaning of that.
Now need to update the following line:
<input type="text" id="txtMessage" **name = "txtMessage"** />
And in the controller code post method the following name should be the same.
[HttpPost]
public ActionResult Create(**string txtMessage**)
{
ViewBag.Message = **txtMessage**;
return View("Index");
}

Model validation in Asp.Net Core before making an Ajax call from java script

Below is the sample code, i am calling this code on button click event. My question is, can i validate my viewmodel object before making ajax call? i can see model errors in java script, not sure how to check.
My viewmodel class properties has Data Annotation Validator Attributes. I don't want make ajax call if the viewmodel is not valid, want to check (ModelState.IsValid) in java script code, before making ajax call.
Any help, would be greatly appreciated.
$(function () {
$("#btnGet").click(function () {
var viewModelobject = {};
viewModelobject.Name = $("#txtName").val();
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: viewModelobject,
contentType: "application/json",
dataType: "json",
success: function (response) {
alert("Hello")
}
});
});
}
ModelState.IsValid is server side code.Browser has no idea about what it is,so you could not validate ModelState in client side. You can use Jquery Validation at client side.
Here is a working demo:
1.Model:
public class UserModel
{
[Required(ErrorMessage = "The Name field is required.")]
[Display(Name = "Name")]
public string Name { get; set; }
}
2.View(Index.cshtml):
#model UserModel
<form id="frmContact">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Name" class="control-label"></label>
<input asp-for="Name" id="txtName" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
<button type="submit" class="btn btn-secondary" id="btnGet">Click</button>
</div>
</form>
#section Scripts
{
#*you could also add this partial view*#
#*#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}*#
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.15.1/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.6/jquery.validate.unobtrusive.min.js"></script>
<script>
$(function () {
$('#btnGet').click(function () {
if ($("#frmContact").valid()) {
$('#frmContact').submit();
}
else {
return false;
}
});
$("#frmContact").on("submit", function (event) {
event.preventDefault();
var viewModelobject = {};
viewModelobject.Name = $("#txtName").val();
$.ajax({
type: "POST",
url: "/Home/AjaxMethod",
data: JSON.stringify(viewModelobject),
contentType: "application/json",
dataType: "json",
success: function (response) {
alert("Hello")
}
});
});
})
</script>
}
3.Controller:
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult AjaxMethod([FromBody]UserModel user)
{
//do your stuff...
return Json(user);
}
}
Result:
Please use jQuery form validation as shown below inside the button click callback:
var form = $('form[name="' + formName + '"]');
form.validate();
if (form.valid()) {
//Do something if the form is valid
}
else {
//Show validation error messages if the form is in-valid
}

How to use ajax to post Kendo upload files to controller

When i use ajax to post the form data to controller, i cannot get the files when using Kendo upload. I used IEnumerable but i only can get the date value and the file is null. May i know how to make it work? Thanks.
(I use ajax because i need call the onsuccess event)
//Here is the form control in view
<div class="editForm">
#using (Html.BeginForm("UpdateReportFix", "Defect", FormMethod.Post, new { id = "form" }))
{
#Html.HiddenFor(model => model.DefectFixID)
<div>
#Html.Label("Report Date")
</div>
<div>
#(Html.Kendo().DatePickerFor(model => model.ReportDate)
.Name("ReportDate")
.Value(DateTime.Now).Format("dd/MM/yyyy")
.HtmlAttributes(new { #class = "EditFormField" })
)
#Html.ValidationMessageFor(model => model.ReportDate)
</div>
<div>
#Html.Label("Photos")
<br />
<span class="PhotosMessage">System Allow 2 Pictures</span>
</div>
<div class="k-content">
#(Html.Kendo().Upload()
.Name("files") <-----i cannot get this value in controller
)
</div>
<br />
<div class="col-md-12 tFIx no-padding">
#(Html.Kendo().Button().Name("Cancel").Content("Cancel").SpriteCssClass("k-icon k-i-close"))
#(Html.Kendo().Button().Name("submit").Content("Submit").SpriteCssClass("k-icon k-i-tick"))
</div>
}
//script
$('form').submit(function (e) {
e.preventDefault();
var frm = $('#form');
$.ajax({
url: '#Url.Action("UpdateReportFix")',
type: 'POST',
data: frm.serialize(),
beforeSend: function () {
},
onsuccess: function () { },
success: function (result) { },
error: function () { }
});
});
For "Uploading files using Ajax & Retain model values after Ajax call and Return TempData as JSON" try the following example:
View:
#using (Html.BeginForm("Create", "Issue", FormMethod.Post,
new { id = "frmCreate", enctype = "multipart/form-data" }))
{
<div id="divMessage" class="empty-alert"></div>
#Html.LabelFor(m => m.FileAttachments, new { #class = "editor-label" })
#(Html.Kendo().Upload()
.HtmlAttributes(new { #class = "editor-field" })
.Name("files")
)
}
<script>
$(function () {
//Populate model values of the partialview after form reloaded (in case there is a problem and returns from Controller after Submit)
$('form').submit(function (event) {
event.preventDefault();
showKendoLoading();
var selectedProjectId = $('#ProjectID').val(); /* Get the selected value of dropdownlist */
if (selectedProjectId != 0) {
//var formdata = JSON.stringify(#Model); //For posting uploaded files use as below instead of this
var formdata = new FormData($('#frmCreate').get(0));
$.ajax({
type: "POST",
url: '#Url.Action("Create", "Issue")',
//contentType: "application/json; charset=utf-8", //For posting uploaded files use as below instead of this
data: formdata,
dataType: "json",
processData: false, //For posting uploaded files we add this
contentType: false, //For posting uploaded files we add this
success: function (response) {
if (response.success) {
window.location.href = response.url;
#*window.location.href = '#Url.Action("Completed", "Issue", new { /* params */ })';*#
}
else if (!response.success) {
hideKendoLoading();
//Scroll top of the page and div over a period of one second (1,000 milliseconds = 1 second).
$('html, body').animate({ scrollTop: (0) }, 1000);
$('#popupDiv').animate({ scrollTop: (0) }, 1000);
var errorMsg = response.message;
$('#divMessage').html(errorMsg).attr('class', 'alert alert-danger fade in');
$('#divMessage').show();
}
else {
var errorMsg = null;
$('#divMessage').html(errorMsg).attr('class', 'empty-alert');
$('#divMessage').hide();
}
}
});
}
else {
$('#partialPlaceHolder').html(""); //Clear div
}
});
});
</script>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Exclude = null)] Model viewModel, IEnumerable<HttpPostedFileBase> files)
{
//...
return Json(new { success = false, message = "Max. file size is 10MB" }, JsonRequestBehavior.AllowGet);
}

passing model from view to controller using jquery

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);
}
});
}

Partial view not rendering MVC razor

It's my first time using partial views and I am unable to get the actual partialview. The ajax function gets called, the controller gets hit, and an alert in the ajax call shows me that the partialview is there. But, with errors written to the console (or alert) my div remains just as empty.
My application is an MVC4 app, but I am pretty sure I've just done a silly mistake somewhere and its not MVC's fault :)
AFter a few hours of googling, I would really be happy anybody can help me get this working, and all tips/comments on code/ajax i greatly appreciated!
public PartialViewResult Groups()
{
var person = _userRepository.GetCurrentUser();
var connections = (from c in person.Person1 select c).ToList();
var groups = _context.Groups.Where(g => g.GroupId == 1);
var all = new GroupViewModel()
{
Connections = connections,
GroupDetailses = (from g in groups
select
new GroupDetails
{
Name = g.Name,
StartDate = g.StartDate,
StartedById = g.StartedById,
})
};
return PartialView("Groups",all);
}
My PartialView
#model Mvc4m.Models.GroupViewModel
<h2>Groups</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<h3>Create new Group</h3>
<div class="ui-widget">
<label for="group">Groupname: </label>
<input id="group" />
<button onclick="addGroup()">Add</button>
</div>
#foreach (var item in Model.GroupDetailses)
{
#Html.LabelFor(model => item.Name)<text> : </text>
#Html.DisplayFor(model => item.Name)
}
<script>
function addGroup() {
$.get(
"/Profile/AddGroup",
{
Name: $("#group").val()
});
location.reload();
};
</script>
My Ajax call on Profile/Index
#model Mvc4m.Models.ProfileView
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<div id="test" style="background-color:Aqua; width:200px; height:100px"></div>
<button onclick="load()"></button>
<script type="text/javascript">
function load() {
$.ajax({
type: "GET",
url: '/Profile/Groups',
dataType: 'html',
success: function (response) {
$('#test').html(response);
alert(response);
},
error: function (xhr, status, error) {
alert(status + " : " + error);
}
});
}
</script>
Turns out the code works, a restart of visual studio did the trick! How I hate VS sometimes...

Resources