Asp.Net Mvc How can i refresh my modal after ajax post - c#

I send a page number to the controller. And I pull the relevant record and make a return view. I send a request to this method with ajax. Since the page is not refreshed after the return view, I cannot print the current records I want on the page. How can I solve this problem?
Controller;
` public IActionResult Index(int pageNumber = 1)
{
_leadDataPagerInputModel.PageNumber = pageNumber;
_leadDataPagerInputModel.PageSize = 10;
ResponseModel<LeadDataDto> responseModel = new ResponseModel<LeadDataDto>();
IResultObjectPagedListModel<LeadDataDto> leadDataResult = _leadDataBusinessManager.GetList(_leadDataPagerInputModel);
if (leadDataResult.IsSuccess)
responseModel.Items = leadDataResult.Data;
responseModel.Success = leadDataResult.IsSuccess;
responseModel.ErrorMessage = leadDataResult.Message;
return View(leadDataResult);
}`
`
onPageClick: function (pageNumber, event) {
$.ajax({
type: "POST",
url: "#Url.Action("Index")",
data: { pageNumber: pageNumber },
success: function (result) {
},
error: function (req, status, error) {
alert(error);
}
});`
Index.cshtml modal
I want new data to come with the page number I sent, but I don't know how to refresh the data on the page.

Related

Ajax Posting twice ASP NET CORE MVC

Controller
[HttpPost]
public IActionResult Index(string mainFin, string actNumber, int actTypeId)
{
int userId = Int16.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier));
Act act = new Act()
{
ActTypeId = actTypeId,
CreateDate = DateTime.Now,
ApproveDate = null,
UserId = userId,
StatusId = 1,
};
_unitOfWork.ActRepository.Add(act);
_notyf.Success("Arayış əlavə edilid !");
_unitOfWork.Complete();
return RedirectToAction("Marriage");
}
AJAX
$(function () {
var actTypeId = $("#questList option:selected").val();
console.log("QuestList ishledi !");
$('#formSubmit').click(function (e) {
var mainFin = $("#FinInput").val();
var actNumber = $("#actNumber").val();
console.log(mainFin);
$.ajax({
url: "/Home/Index",
type: "POST",
data: { mainFin: mainFin, actNumber: actNumber },
success: function (data) {
console.log("+++++");
},
error: function () {
console.log("------");
}
});
e.preventDefault();
$("#questForm1").submit();
});
});
Problem : When I click submit button data inserts twice to database (AJAX makes 2 request at same time )
If you want to submit the form via AJAX then you need to remove the last line of the click event handler.
$("#questForm1").submit();
This line is submitting the form and essentially negating the e.preventDefault() above.
You are submitting your data twice: at first using ajax and after that using using the form submit.
You have to remove one of them, I would guess the form submit.
Also, since ajax is called async, if you want to do something after ajax has been called and returned successfully, you have to put the code in success section.
So the code should look like:
$(function () {
var actTypeId = $("#questList option:selected").val();
console.log("QuestList ishledi !");
$('#formSubmit').click(function (e) {
e.preventDefault();
var mainFin = $("#FinInput").val();
var actNumber = $("#actNumber").val();
console.log(mainFin);
$.ajax({
url: "/Home/Index",
type: "POST",
data: { mainFin: mainFin, actNumber: actNumber },
success: function (data) {
console.log("+++++");
// do your thing here, once the ajax requst has returned successfully
},
error: function () {
console.log("------");
}
});
// NOTICE: form submit removed
});
});

How to display succes or error message in MVC with Javascript?

I'm wondering how to display a succes or error message on succes or fail by a controller action in my MVC project with bootstrap. For example I got the following action:
Input:
Javascript method to send data to controller:
//Sends data filled in in modal to backend.
$(document).ready(function () {
$("#btnSubmit").click(function () {
var datastring = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "/ApiBroker/AddApi",
dataType: 'json',
data: datastring,
});
$('#myModal').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
})
})
Controller method:
[HttpPost]
public ActionResult AddApi(ApiRedirect model)
{
var data = model;
try
{
List<ApiRedirect> list = dbProducts.ApiRedirects.ToList();
int companyID = dbProducts.Companies.Where(x => x.CompanyName == model.Company.CompanyName).FirstOrDefault().CompanyID;
int mappingID = dbProducts.MappingNames.Where(x => x.Name == model.MappingName.Name).FirstOrDefault().MappingID;
ApiRedirect api = new ApiRedirect();
api.ApiName = model.ApiName;
api.CompanyID = companyID;
api.ApiURL2 = model.ApiURL2;
api.MappingID = mappingID;
api.ResponseType = model.ResponseType;
dbProducts.ApiRedirects.Add(api);
dbProducts.SaveChanges();
return View ();
}
catch (Exception ex){
throw ex;
}
}
If the method AddUser added the user into my database I want to display a error message, and if the user was not added I want to display a error message. I dont know how to achieve this, any suggetions?
Thanks in advance!
UPDATE
So the alert works but the POST call is getting the following internal server error:
Firstly you ajax needs to be updated to use a success or failure
$.ajax({
type: 'POST',
url: "/ApiBroker/AddApi",
data: datastring,
dataType: 'json',
success:
function(data){
//... put your logic here
},
error:
function(){ alert('error'); }
});
Secondly you need to update your controller action to return a IHttpActionResult where you can specify a Response message.
If you look at this
HttpResponseMessage

Redirect in .Net Core Application

im trying to do some operation .Net Core and after this operation is done, i want to redirect it to a .cshtml page. In homepage i have table, after selecting a row in the table, im sending the value of the cell with ajax.
AJAX
$('#table').find('tr').click(function () {
var userName = $(this).find('td').text();
$.ajax({
url: "/Profile/printUser",
type: 'POST',
data: { "DisplayName": userName }
});
});
After this part, im going to this area
FUNCTION
[HttpPost]
public IActionResult printUser(User user)
{
user.DisplayName = user.DisplayName.Replace("\n", String.Empty);
user.DisplayName = user.DisplayName.Trim(' ');
User findUser = UserAdapter.GetUserByUserName(user.DisplayName);
return RedirectToAction("ProfileScreen",findUser);
}
My operations are finished, i found my user. All i want to do is print this users information in cshtml. But i cant send myselft to the page. How can i redirect myself? Thanks.
INDEX
public IActionResult ProfileScreen()
{
return View();
}
You can't redirect from Ajax call in the backend. Use AJAX's
success: function(){
windows.location.href = '/ProfileScreen';
}
If you want to pass data back, return JSON from MVC action and your JavaScript would be:
$('#table').find('tr').click(function () {
var userName = $(this).find('td').text();
$.ajax({
url: "/Profile/printUser",
type: 'POST',
data: { "DisplayName": userName },
success: function(data){
window.location.href = '/ProfileScreen' + data.ID; //or whatever
}
});
});
SOLUTION
FUNCTION
[HttpPost]
public JsonResult printUser(User user)
{
user.DisplayName = user.DisplayName.Replace("\n", String.Empty);
user.DisplayName = user.DisplayName.Trim(' ');
User findUser = UserAdapter.GetUserByUserName(user.DisplayName);
return Json(new { displayName = findUser.DisplayName});
}

form submit and redirect to same page with no re render

I have a huger web form in my MVC app.
When I click my "save" button, the form is submitted and the values saved, and at the end I redirect to the same page/form.
But it re renders the whole form, when it was already loaded and there is no need.
How can I avoid that?
I want the SAVE button to behave like: save all but continue where I was.
My controller code:
[HttpPost]
[ValidateInput(false)]
public ActionResult FormCol(FormCollection collection)
{
...
if (Request.Form["DocumentId"] != null)
{
...
return RedirectToAction("FormCol", new { id = DocumentId });
}
View:
<input type="hidden" value="#document.Id" name="DocumentId" />
You will need to post your form via Ajax / jquery:
$.ajax({
url: '/someController/FormCol?variable1=' + $("#input1").val() + '&variable2=' + $("#input2").val(),
type: 'POST',
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data); //This is where you would do something based upon a successful save, such as alerting the user to their new document ID or something.
},
error: function () {
alert("error"); //This is where you know that your save failed.
}
});
And change your Controller action return Json:
public JsonResult FormCol(string variable1, string variable2)
{
//do saving stuff here
return Json(new { id = DocumentId });
}

Ajax to MVC controller. Not passing parameters unless Ajax followed by alert

I have the strangest situation. I have two ajax POST. First I had problems passing the parameters to the controller but at some point I got them trough and with some debugging I figured out that I only get all of the values to the controller if my ajax definition is followed by an alert.
One of them:
$.ajax({
type: 'POST',
url: '/Contact/IntresseAnmälan/',
dataType: 'json',
data: {
Namn: $('#namn').val(),
Mail: $('#mail').val(),
Info: $('#meddelande').val(),
Telefon: $('#nr').val(),
IsEnkel: false,
PassId: function () {
var url = window.location.pathname;
var id = url.substring(url.lastIndexOf('/') + 1);
return id;
},
Participanter: getParticipant(),
ParticipantMail: getParticipantMail()
},
traditional: true,
success: function (result) {
// window.location.href = '#Url.Action("IntresseAnmälan", "Contact")';
}
});
alert("Hur sparas dina uppgifter?");
Here are my Getters for name and mail. The form-elements(input type mail and text) theese are dynamicly added to the form if the user wants clicks a button two inputs are added. Then theese functions returns an array with the inputed values from the form.
function getParticipant() {
var p = [];
for (var i = 1; i <= participantCount; i++) {
var name = '#anNamn' + i;
p[i -1] = $(name).val()
}
return p;
}
function getParticipantMail() {
var p = [];
for (var i = 1; i <= participantCount; i++) {
p[i -1] = $('#anMail' + i).val();
}
return p;
}
And here is my controller. I've removed the body in the controller. It saves to the Db and send a verification mail to the admin.
[HttpPost]
public ActionResult IntresseAnmälan(BokningContainer bokning)
{
//Saves to Db and Send a verification mail to admin
}
If I exclude the alert after the ajax some parameters are passed, I think it's Namn and Mail, but most of them not passed. I'm quite puzzled.
Also, is ajax the only way to pass an object to a controller from jQuery?
Also, is ajax the only way to pass an object to a controller from
jQuery?
No, you can use a regular HTML Form to submit your data, you just have to conform to the expected object in the controller Action (should be decorated with HttpPostAttribute) - There is a Model-Binding process which attempting to bind the Request data to your domain object.
You don't need to pass every field's value using jQuery. Instead you can create a form whose data you want to post like :
<form id="frmTest">
... add input types here
</form>
and you can pass data of form using $('#frmTest').serialize() method to the controller
$.ajax({
type: "POST",
data: $('#frmTest').serialize(),
url: "url",
dataType: "json",
success: function (data) { alert('worked!'); },
error: function (data) {
alert('error');
}
});

Categories

Resources