Partial View is not rendering properly, after JQuery Ajax submit - ajax

I submit a form post in Asp.Net MVC Partial View with JQuery Ajax.
The Partial View is inside one of the tabs in bootstrap tabs (there is 4 tabs and each tab has its Partial View). And there is a View, which covers all these tabs. And there is a Layout which covers all.
This is Partial view Action method call inside the cover View:
#Html.Action("AddProductPartial", "Products")
Partial View Action:
[HttpPost]
public ActionResult AddProductPartial(ProductCategoryBrand pcb)
{
if (ModelState.IsValid)
{
Product p = new Product();
p.CategoryID = Convert.ToInt32(pcb.CategoryViewModel.Kategori);
p.BrandID = Convert.ToInt32(pcb.BrandViewModel.BrandName);
p.ExchangeName = pcb.ExchangeViewModel.ExchangeName;
ProductRepository prep = new ProductRepository();
prep.AddProduct(p)
}
loadBrands();
getRates();
return View(pcb);
}
JQuery Ajax:
$('#saveProduct').click(function () {
$.ajax({
url: "/Products/AddProductPartial",
type: 'POST',
data: "{'CategoryID':" + categoryID + ", 'BrandID':" + brandID + ",'ExchangeName':" + exchangeName + "}",
async:true,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert("success");
},
error: function (xhr, status, error) {
alert(xhr.responseText)
}
});
});
These statements below populates dropdownlisfor from db. I added these methods because dropdownlistfor in the partial view was giving null exception after Ajax submit.
loadBrands();
getRates();
After adding these statements, the problem occured.
After submit, Partial view is rendering weird: Bootstrap nav-tabs are no longer visible. Because the View that covers the Partial view is not rendering at all. When I change this line:
return View(pcb);
to
return Partial View(pcb);
Then renders only the Partial view itself, independently from the all layout.
Could you please help. Thanks.

Here is the simplest example of partial view:
public class HomeController : Controller
{
[HttpPost]
public PartialViewResult GetXlFile()
{
return PartialView("_ExcelGrid");
}
public ActionResult GetXlFile(int? id)
{
return View();
}
_ExcelGrid.cshtml in shared:
A Partial View Info
View:
<!DOCTYPE html>
#*credit to
https://stackoverflow.com/questions/5410055/using-ajax-beginform-with-asp-net-mvc-3-razor*#
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index800</title>
<script src="~/Scripts/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
$('#pvButton').click(function (event) {
$.ajax({
url: this.action,
type: "POST",
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
return false;
});
});
</script>
</head>
<body>
<form>
<div>
<input id="pvButton" type="button" value="OK" />
<div id="result"></div>
</div>
</form>
</body>
</html>

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.

Can't load data using Ajax for Razor Pages

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

Changing a PageModel property without using handler in Razor Pages

I'm developing a web application using Asp.Net Core Razor Pages.On the page model I have the following property:
public class SchoolModel : PageModel
{
[BindProperty]
public School SchoolEdit { get; set; }
I'd like to change the Logo property of SchoolEdit(of type School) when I click a button on the form without having the form posted.How can I accomplish this?
Here's the razor page code:
#if (Model.SchoolEdit.Logo != null)
{
<button class="btn btn-danger" asp-page-handler="RemovePhoto">
<span aria-hidden="true">×</span>
</button>
}
Later,I defined the following Ajax to change the property when the button is clicked,but the OnPostRemovePhoto doesn't get hit!
#section Scripts {
<script>
$(function () {
$("#Click").click(function () {
$.ajax({
type: "POST",
url: "./School?handler=RemovePhoto",
error: function (response) {
alert('hi');
},
success: function (response) {
alert('error');
}
});
});
})
</script>
Thanks to the same thread on Asp.Net,I figured out the issue.
The anti-forgery token was missing.The AJAX method below sets the token in the header.
Here's the answer:

ajax call with jquery asp.net mvc

I have a button with the class "btn" and span with id "ajaxtest". When I click on the button I want to put text "test" in my span tag. And this to be done in ASP.NET MVC.
In the View I have the following ajax call:
<span id="ajaxtest"></span>
<input type="submit" class="btn" name="neverMind" value="Test BTN"/>
<script>
$(document).ready(function () {
$(".btn").click(function () {
$.ajax({
method: "get",
cache: false,
url: "/MyController/MyAction",
dataType: 'string',
success: function (resp) {
$("#ajaxtest").html(resp);
}
});
});
});
</script>
In MyController I have the following code:
public string MyAction()
{
return "test";
}
I know how Ajax works, and I know how MVC works. I know that maybe the error is because we are expecting something like this in the controller:
public ActionResult MyAction()
{
if (Request.IsAjaxRequest())
{
//do something here
}
//do something else here
}
But actually that is my problem. I don't want to call some partial View with this call. I just want to return some string in my span and I'm wondering if this can be done without using additional partial views.
I want to use simple function that will only return the string.
Change dataType: 'string' to dataType: 'text'
<script>
$(document).ready(function () {
$(".btn").click(function () {
$.ajax({
method: "get",
cache: false,
url: "/login/MyAction",
dataType: 'text',
success: function (resp) {
$("#ajaxtest").html(resp);
}
});
});
});
</script>
I check it my local it will work for me

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

Resources