Can't load data using Ajax for Razor Pages - ajax

I have this ajax call in my view, Form.cshtml
<form id="myForm">
<input id="btnSubmit" type="submit" value="Load data" />
<p id="result"></p>
</form>
#section scripts{
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function () {
debugger
$.get('/Form/',function (data) {
debugger
console.log('test');
});
})
});
</script>
}
and in my Razor Pages code behind, Form.cshtml.cs
public class FormModel : PageModel
{
public JsonResult OnPost()
{
List<Student> students = new List<Student>{
new Student { Id = 1, Name = "John"},
new Student { Id = 2, Name = "Mike"}
};
return new JsonResult(students);
}
}
The problem is it doesn't reach OnPost method. If I put in OnGet, it will automatically load before I click the Submit button.
I try to create another Razor page called Filter.cshtml and in Filter.cshtml.cs. And then in my Form.cshtml, I changed my url to /Filter/, it did reach OnGet in Filter.cshtml.cs
public class FilterModel : PageModel
{
public JsonResult OnGet()
{
List<Student> students = new List<Student>{
new Student { Id = 1, Name = "John"},
new Student { Id = 2, Name = "Mike"}
};
return new JsonResult(students);
}
}

The default behaviour of clicking a submit button in a form is that the form gets submitted. At the moment, your form has no method specified, so the submission will default to the GET method. If you want to submit the form by AJAX POST rather than the usual behaviour, you need to do two things:
Cancel the default action of the button click (which is what currently causes the OnGet handler to execute)
Change the jQuery code to use the POST method:
#section scripts{
<script type="text/javascript">
$(function () {
$('#btnSubmit').click(function (e) { // include the event parameter
e.preventDefault(); // prevents the default submission of the form
$.post('/Form/',function (data) { // change from 'get' to 'post'
console.log('test');
});
});
});
</script>
}

the $.get() makes Ajax requests using the HTTP GET method, whereas the $.post() makes Ajax requests using the HTTP POST method.
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/Filter/OnGet",
success: function (result) {
}
});

Related

Asp.net core controller function with return partial view with select2 not working and remote function validation is not firing in modal popup

Select2 is not working and remote validation is not firing, this is only happens when I convert the code to modal popup but if not everything is working properly. What Am I missing in my code? Any advise or help much appreciated.. Thank you
Here is my code the modal:
$('#tbProducts tbody').on('click', 'button', function () {
var data = productsTable.row($(this).parents('tr')).data();
//alert(data.id);
$.ajax({
url: '#Url.Action("Edit", "Products")',
type: 'GET',
data: { id: data.id },
success: function (result) {
$('#EditUnitModal .modal-content').html(result);
$('#EditUnitModal').modal()
}
});
});
Here is the controller edit code:
public async Task<IActionResult> Edit(int? id)
{
//code here
return PartialView("__Edit", product);
}
And here is my partial view __Edit code:
#model intPOS.Models.Master.ViewModel.ProductViewModel
//code here
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
<script type="text/javascript">
$(function () {
$('#Unit').select2({
theme: 'bootstrap4',
dropdownParent: $('#EditUnitModal')
})
$('#Category').select2({
theme: 'bootstrap4',
dropdownParent: $('#EditUnitModal')
})
})
</script>
}
And View model code:
[Display(Name = "Product Code"), Required]
[Remote("CheckProduct", "Products", AdditionalFields = "Id", ErrorMessage = "Product already exists.")]
public string ProductCode
{
get
{
return _productcode;
}
set
{
_productcode = value.Trim();
}
}
Sample screen for not firing validation and select2 is not working:
sections aren't allowed in partial views. You can still use modals and partial views via Ajax for edit forms but there is a small modification you need to do in order for this to work:
Include all the necessary scripts in your page (this is mandatory as sections aren't allowed in partial views).
In your javascript code add these lines in order to parse the new form via jquery validation unobtrusive and your select elements via Select2.
$('#tbProducts tbody').on('click', 'button', function () {
var data = productsTable.row($(this).parents('tr')).data();
//alert(data.id);
$.ajax({
url: '#Url.Action("Edit", "Products")',
type: 'GET',
data: { id: data.id },
success: function (result) {
$('#EditUnitModal .modal-content').html(result);
//Here we parse the new form via jquery validation unobtrusive.
$.validator.unobtrusive.parse($('#EditUnitModal .modal-content form')[0]);
//Here we initialize select2 for the selected elements.
$(".yourSelect2ElementClass").select2({//options...});
//Now we launch the modal.
$('#EditUnitModal').modal()
}
});
});
Don't forget to remove the section from your partial view and include your scripts in the containing view.

Ajax request off an MVC Form

I am trying to do an ajax request and depending on the ajax request results I will allow the form to submit to the controller. However everytime the ajax request runs I get the error message.
Here is my javascript function:
function CheckForValidation(e) {
var scholarshipRequest = $("#scholars").val();
var aidYearRequest = $("#aidYear").val();
var amountRequest = $("#amount").val();
$.ajax({
type: "POST",
url: '#Url.Action("Validate_ScholarshipRequest", "RequestController")',
data: {
scholarshipId: scholarshipRequest,
aidYear: aidYearRequest,
amount: amountRequest
}
}).success(function(response) {
if (!response.success) {
e.preventDefault();
alert(success);
} else {
e.preventDefault();
}
}).error(function() {
e.preventDefault();
alert("Error on Submission");
});
}
This function is called from here:
$("#SubmitTutorRequestFrm").submit(function(e) {
e.PreventDefault();
CheckForValidation(e);
});
I try to debug the code and put a breakpoint on Validate_ScholarshipRequest but that method never gets called. The method signature is:
public ActionResult Validate_ScholarshipRequest(string scholarshipId, string aidYear, string amount)
This is the start of my form:
#using (Html.BeginForm("SubmitScholarshipRequest", "Request", FormMethod.Post, new { id = "SubmitTutorRequestFrm" }))
Just to get this officially answered and "closed", this was caused by a syntax-error:
url: '#Url.Action("Validate_ScholarshipRequest", "RequestController")',
Controller should not be included in the controller name. The correct action would then be:
url: '#Url.Action("Validate_ScholarshipRequest", "Request")',

Update ViewBag dropdownlist with ajax

I am working on cascaded dropdownlist with data passed with dataview.
Controller:
public ActionResult Index()
{
ViewBag.States = new SelectList(db.PLStates, "PLStateID", "PLStateName");
ViewBag.Cities = new SelectList(db.PLCitys, "PLCityID", "PLCityName");
return View();
}
[HttpPost]
public JsonResult GetCity(int SelectedStateId)
{
SelectList result = new SelectList(db.PLCitys.Where(x => x.PLStateID == 3), "PLCityID", "PLCityName");
return Json(result);
//return Json(ViewBag.Cities = new SelectList(db.PLCitys.Where(x => x.PLStateID == 3), "PLCityID", "PLCityName"));
}
HTML:
<script type="text/javascript">
$(document).ready(function () {
$("#States").change(function () {
var SelCity1 = $("#States").val();
$("#Cities").empty();
$.ajax({
type: 'POST',
url: '#Url.Action("GetCity")',
dataType: 'JSON',
data: { SelectedStateId: SelCity1 },
success: function (Cities) {
ViewBag.Cities = Cities;
$("#Cities").append('Cities');
alert("success" + Cities);
},
error: function (ex) {
alert('Failed to retrieve states.' + ex);
}
});
return false;
})
});
</script>
<div>
#Html.DropDownList("States", "Select one")
#Html.DropDownList("Cities", "Select one")
</div>
In alert i can see the json gives back objects but the Cities dropdownlist becomes emptied with no value inside. Why ddl.cities is not filled with retured values??
Additional question is how to add style to dropdownlist??
You will have to manually add options to the cities drop down via js with the Json data returned from the controller.
As far as styling. You can style in inline by adding a "style"= to the html attributes or style with external css class using the #class html attribute.

How to upload a file without reloading the whole page in mvc3?

I have been working with MVC for the past few days.
I have a problem in one of my pages, i.e I have a page where q user enters the required details and uploads a file. I have two buttons named Upload for Uploading File and Create for creating new profile.
My Problem
My problem is I don't want to reload the whole page when user clicks on upload button. I was thinking of using an webmethod for fileupload.
I don't know if what am I doing wrong here
Can any one correct me
This is my Webmethod in my controller named Create
Controller
[WebMethod]
public string FileUpload(HttpPostedFileBase file, BugModel model)
{
BugModel bug = null;
if (file != null && file.ContentLength > 0)
{
string path = "/Content/UploadedFiles/" + Path.GetFileName(file.FileName);
string savedFileName = Path.Combine(System.Web.HttpContext.Current.Server.MapPath ("~" +path));
file.SaveAs(savedFileName);
BugAttachment attachment = new BugAttachment();
attachment.FileName = "~" + path.ToString();
bug.ListFile.Add(attachment);
model = bug;
}
return "FileUploaded";
}
used a script to call the method
Javascript
<script type="text/javascript">
function UploadFile() {
$.ajax({
type:"Post",
url: "LogABug/FileUpload",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("File Uploaded")
},
error: function () {
ErrorMessage("Try Again");
}
});
}
</script>
can any one tell me how can I do this ...if this is the wrong method correct me the right one with the ideas please
You are uploading the file separately. Therefore you will need two actions:
public string Something(BugModel model) for the model.
public string FileUpload(HttpPostedFileBase file) for the file
Now, I would use jQuery Form Plugin for ajax submitting. Here is an example:
<script type="text/javascript">
$(function () {
$("#file-upload-form").submit(function () {
$(this).ajaxSubmit({
target: "#message",
cache: false
});
return false;
});
});
</script>
#using(Html.BeginForm("FileUpload", "LogABug", FormMethod.Post, new { enctype = "multipart/form-data", id = "file-upload-form" })) {
#Html.ValidationSummary(true)
<fieldset>
#Html.EditorFor(model => model.File)
<input type="submit" value="Upload" />
</fieldset>
}
<div id="message">
</div>
What ever you return from your action will be displayed in the div with id message

MVC submit form outside ajax.beginform

I have a certain ajax form and when submitted I want to include another form outside of that ajax form. Let me show you an example:
#using (Ajax.BeginForm("PayWithBankTransfer", "Payment", new { salesLineId = salesLine.SalesLineID }, new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "bankForm",
LoadingElementId = "spinnerBank"
}, new { id = "feedback-form" }))
{
//some stuff
<button type="submit">Reserve</button>
}
I have another tag outside of the form I want to include in the ajax form submission
<div id="theOtherStuff">
//otherStuff
</div>
How could I submit the other stuff along with the ajax form?
I don't think that MS unobtrusive AJAX supports this. So let's get rid of it and use plain jQuery. The .serialize() method is what you are looking for.
So we start by replacing the Ajax.BeginForm form with a regular Html.BeginForm
#using (Html.BeginForm(
"PayWithBankTransfer",
"Payment",
new { salesLineId = salesLine.SalesLineID },
FormMethod.Post,
new { id = "feedback-form" })
)
{
//some stuff
<button type="submit" class="t-button t-state-default" style="width: 100px; height: 50px;">Reserver</button>
}
then we provide an id to the other form so that we can reference it in our script:
<div id="theOtherStuff">
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "theOtherStuffForm" }))
{
//otherStuff
}
</div>
and all that's left is write our script in a separate javascript file to unobtrusively AJAXify this form:
$(function() {
$('#feedback-form').submit(function () {
$('#spinnerBank').show();
$.ajax({
url: this.action,
type: this.method,
data: $(this).add('#theOtherStuffForm').serialize(),
success: function (result) {
$('#bankForm').html(result);
},
complete: function () {
$('#spinnerBank').hide();
}
});
return false;
});
});
The following line should be of particular interest:
data: $(this).add('#theOtherStuffForm').serialize(),
As you can see the .serialize method allows convert multiple forms into suitable serialized form.
It is more than obvious that you should not have conflicting names with the input elements of the 2 forms (for example have 2 elements with the same name), otherwise the default model binder could go berserk. It's up to you to resolve those conflicts if there are any.

Resources