I have a form in which I am posting data using ajax using jquery. Problem is, when I alert #Model.Id or when I try to pass the value in FormData in the view, I can't see the alert and when I keep the breakpoint in the Controller, I get the breakpoint fine upon clicking the Post Comment button. I also get all values on the form except for the Id Please help.
(And please see the document ready function, there I can access the Id fine. Only when I click the Post Comment button, I have the problem with the Id.)
Here is my View
#model KGSBlog.Models.BlogData
#{
Layout = null;
}
<html>
<body>
<form id="formPostComment" method="post" asp-controller="BlogData" asp-action="PostComment">
<div class="row">
<div class="col-md-6">
<input type="text" placeholder="Name *" name="name" required>
</div>
<div class="col-md-6">
<input type="email" placeholder="Email *" name="email" required>
</div>
</div>
<textarea name="message" placeholder="Message *" id="message" cols="45" rows="10" required></textarea>
<button type="submit" id="btnPostComment" class="btn btn-main m-bottom-40">Post Comment</button>
</form>
<!-- jQuery -->
<script src="~/js/jquery.min.js"></script>
<!-- Bootstrap -->
<script src="~/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
LoadPartialView(#Model.Id); //Here I can access the Id fine.
$('#formPostComment').validate({
rules: {
name: {
required: true,
minlength: 4
},
email: {
required: true,
email: true
},
message: {
required: true,
minlength: 10
}
}
});
});
$(function () {
$("#btnPostComment").click(function () {
alert(#Model.Id); // I cannot see this alert.
var url = $("#formPostComment").attr("action");
var formData = new FormData();
formData.append("Name", $("#name").val());
formData.append("Email", $("#email").val());
formData.append("Comment", $("#message").val());
formData.append("BlogId", #Model.Id); //This value is always 0.
$.ajax({
type: 'POST',
url: url,
data: formData,
processData: false,
contentType: false,
success: function (response) {
LoadPartialView(response.blogId);
$('#formPostComment')[0].reset();
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
function LoadPartialView(blogId) {
$.ajax({
type: 'POST',
url: "/BlogData/UpdateCommentsPartial",
data: { "blogId": blogId },
success: function (data) {
$("#haveToReloaddiv").html(data);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
})
}
</script>
</body>
</html>
When I hit the Post Comment button I see the break point in the Controller action method with all the values of the form, but the Id is always 0.
Related
I have this issue with autocomplete, it returns something like this:This
But when you check what returns post method everything is as it should be but in view we get in return just blank field, instead of word "Hardware".
My Code:
Constructuor Method:
[HttpPost]
public JsonResult CreateJS(string prefix)
{
List<CategoryModel> list = new List<CategoryModel>();
list = _context.Categories.ToList();
var CatList = (from N in list
where N.Name.StartsWith(prefix)
select new { value = N.Name,label = N.Name });
return Json(CatList);
View:
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(document).ready(function () {
$("#Category").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Incident/CreateJS",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.Name, value: item.Name };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="IncidentDescription" class="control-label"></label>
<input asp-for="IncidentDescription" class="form-control" />
<span asp-validation-for="IncidentDescription" class="text-danger"></span>
</div>
<div class="form-group">
<label asp-for="Title" class="control-label"></label>
<input asp-for="Title" class="form-control" />
<span asp-validation-for="Title" class="text-danger"></span>
</div>
<div class="form-group">
<label for="Category">Cat:</label>
<input type"text" name="Category" id="Category"/>
</div>
There is no need to use $.map in the ajax callback functiom. Directly apply the data to the response.
<script>
$(document).ready(function () {
$("#Category").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Incident/CreateJS",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response(data);
}
})
},
});
})
</script>
I need to create a newsletter form in my footer, so I had to include it in my layout.
I have successfully created the form using:
<footer>
<form method="post" asp-controller="NewsletterSubscriptions" asp-action="Create" data-ajax="true" data-ajax-method="post" data-ajax-success="success" data-ajax-completed="completed">
<div class="newsletter" id="newsletter">
<div class="form-group">
<input type="text" id="FullName" name="FullName" data-provide="FullName" class="form-control" placeholder="name" autocomplete="off">
</div>
<div class="form-group">
<input type="email" id="Email" name="Email" data-provide="Email" class="form-control" placeholder="email" autocomplete="off">
</div>
</div>
<div class="newsletter-btn">
<input type="submit" value="ok" />
</div>
</form>
</footer>
And in Head:
<head>
<script src="#Url.Content("/lib/jquery-validation/dist/jquery.validate.js")"></script>
<script src="#Url.Content("/lib/jquery-validation/dist/additional-methods.js")"></script>
<script src="#Url.Content("/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js")"></script>
<script>
success = function () {
alert("Hi !");
};
</script>
<script>
completed = function (xhr) {
alert("Hi ${xhr.responseText}!");
};
</script>
</head>
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("FullName,Email")] NewsletterSubscription newsletterSubscription)
{
if (ModelState.IsValid)
{
_context.Add(newsletterSubscription);
await _context.SaveChangesAsync();
return Redirect(Request.Headers["Referer"]+ "#newsletter");
}
else
return View(newsletterSubscription);
}
When I submit, page is refreshed, form is submitted successfully, user is redirected to same page footer area.
But success, or completed functions are not triggered. what am I doing wrong?
Write your form tag as follows:
<div id="success-message-container" class="alert alert-success text-center d-none">
<strong>Success!</strong> You have been subscribed successfully!
</div>
<div id="failure-message-container" class="alert alert-danger text-center d-none">
<strong>Failure!</strong> There is some problem with the service.Please try again.If the problem persists
please contract with system administrator!
</div>
<form id="newsLetterForm" method="post" asp-controller="NewsletterSubscriptions" asp-action="Create">
// Your form contents
</form>
Then in the JavaScript :
$(document).on("submit", "#newsLetterForm", function (event) {
event.preventDefault();
event.stopImmediatePropagation();
var formData = new FormData(this);
var url = this[0].action; // if this does not work then use '#Url.Action("Create","NewsletterSubscriptions")'
$.ajax({
url: url,
type: 'POST',
data: formData,
success: function (response) {
if (response) {
document.getElementById("newsLetterForm").reset();
$("#newsLetterForm input,textarea").removeClass('valid');
$("#success-message-container").removeClass("d-none");
setTimeout(function () {
$("#success-message-container").addClass("d-none");
}, 5000);
}
},
error: function () {
$("#failure-message-container").removeClass("d-none");
setTimeout(function () {
$("#failure-message-container").addClass("d-none");
}, 5000);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Note: css classes I have used is from Bootstrap 4
I've a parent view which contains a table of data. This View contains two modal dialog as shown in below code:-
<div id='myModal' class='modal fade in' data-keyboard="false" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content" style="width: 400px; height:250px;">
<div id='firstModelContent'></div>
</div>
</div>
</div>
<div class="modal fade" tabindex="-1" id="callBackModal" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog">
<div class="modal-content" style="width: auto;">
<div id='secondModalContent'></div>
</div>
</div>
</div>
On each row click of table, firstModal dialog will popup with row data as parameter. Now the requirement is to initiate the second modal popup from the "submit button" of first modal.
I'm able to load a partial view as the firstmodal dialog with row parameters using AJAX. But I'm unable to load a partial view as secondmodal dialog on a button click of firstmodal partial view. Instead while debugging the secondmodal doesn't gets checked. It will simply redirect to partial view on a full screen page. The html link that gets auto-generated from the firstmodal dialog partial view looks like below:-
<a class="btn btn-primary" data-modal="" href="/SampleController/Update?ID=867448&status=Yes" title="Update Details">Yes</a>
And the AJAX code for second modal is like below **in the parent page JavaScript **:-
$(function () {
$("a[data-modal]").on("click", function (e) {
debugger;
var $buttonClicked = $(this);
//var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: '#Url.Action("Update", "SampleController")',
contentType: "application/json; charset=utf-8",
data: { "Id": id },
datatype: "json",
success: function (data) {
debugger;
$('#myModalContent').html(data);
$('#callBackModal').modal(options);
$('#callBackModal').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
//$("#closbtn").click(function () {
// $('#callBackModal').modal('hide');
//});
});
});
But the first modal popup on "button" click doesn't open the second modal pop.
Can anyone please suggest how to perform this operation?
Looking forward to hearing from you.
When you click the link :
<a class="btn btn-primary" data-modal="" href="/SampleController/Update?ID=867448&status=Yes" title="Update Details">Yes</a>
it will not execute your ajax call.
You must change it to "button" :
<button type="button" class="btn btn-primary btn-yes">Yes</a>
jQuery:
$(".btn-yes").on("click", function (e) {
var $buttonClicked = $(this);
//var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: '#Url.Action("Update", "SampleController")',
contentType: "application/json; charset=utf-8",
data: { "Id": id },
datatype: "json",
success: function (data) {
debugger;
$('#myModalContent').html(data);
$('#callBackModal').modal(options);
$('#callBackModal').modal('show');
},
error: function () {
alert("Dynamic content load failed.");
}
});
I am trying to send the value of <textarea> to a method in some controller but doesn't run well. I will post the code to make it clear:
Here is the method
public ActionResult SubmitText(string txtRendered)
and here is the ajax to call
$.ajax({
url: '/Form/SubmitText',
type: 'Get',
dataType: 'json',
data: { txtRendered: $("textarea#render").val() },
success: function (data) {
alert("success");
},
error: function () {
alert('error');
}
});
and here is the textarea
<textarea id="render" name="txtRenderd" class="span6">
<form class="form-horizontal" >
<fieldset>
<legend>Form Name</legend>
<div class="control-group">
<label class="control-label" for="textinput-0">Text Input</label>
<div class="controls">
<input id="textinput-0" name="textinput-0" type="text" placeholder="placeholder" class="input-xlarge">
<p class="help-block">help</p>
</div>
</div>
</fieldset>
</form>
</textarea>
actually it is complicated, since I am trying to pass a form as a text as you can see
In my view I have a modal window, it have the next form...
#using (Html.BeginForm("controllerAction", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div class="container" id="editRecordForm">
<div class="row">
<div class="col-md-6">
#Html.LabelFor(model => model.Author)
#Html.TextBoxFor(model => model.Author, new { #class = "form-control", #style = "height:auto" })
#Html.ValidationMessageFor(model => model.Author)
</div>
</div>
<br/>
<div class="row">
<div class="col-md-6">
#Html.LabelFor(model => model.Image)
<input type="file" name="file" accept="image/*">
</div>
</div>
<br />
<input type="submit" value="Submit" class="btn btn-primary">
</div>
}
this is the JS that contains the ajax request
<script>
var formdata = new FormData($('form').get(0));
$('form').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
cache: false,
data: formdata,
success: function (status, data) {
console.log(data);
}
});
}
return false;
});
</script>
The action controller receives two parameters the model and file
[HttpPost]
public async Task<JsonResult> controllerAction(HttpPostedFileBase file, Model model)
{
var json = new
{
Success = true,
StatusCode = "200",
ErrorDesc = "OK",
ErrorCode = "",
NewId = ""
};
//some process
return Json(json, JsonRequestBehavior.AllowGet);
}
The problem is why when the controller action finish, it redirects to the action controller url
http://controller/action
and it does not stay on the same page?
What Im doing wrong?
You are not preventing the default action of the form.
$('form').submit(function (e) {
e.preventDefault();
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
cache: false,
data: formdata,
success: function (status, data) {
console.log(data);
}
});
}
return false;
});
The problem was the bad config on the javascript- ajax part
$('form').submit(function () {
var formdata = new FormData($('form').get(0));
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
cache: false,
processData: false,
contentType: false,
data: formdata,
success: function (status, data) {
console.log(data);
}
});
}
return false;
});
thanks to Stephen for the help.