Answer the question
In order to leave comments, you need to log in
How to handle ajax form response?
The page has a table and a form that allows you to add an entry to the database. The form is sent to the server with an ajax request. You need to validate the form on the server. If there are errors in it, pass the model from the controller back to the form and display a description of the errors. If there are no errors in the form, update the table.
This is how the controller works:
[HttpPost]
public ActionResult Add(NewsViewModel news)
{
if (ModelState.IsValid)
{
//сохраняем все в бд...
return View('NewsList', db.News);
}
return View(news);
}
Answer the question
In order to leave comments, you need to log in
Use JSON to pass data from the script.
For example :
var success = 'Ваше сообщение успешно доставлено! </br> Благодарим за обращение :)'
$('form').submit(function(e){
var form = $(this);
$.ajax({
type: form.attr('method'),
data: form.serialize(),
dataType: "json",
url: form.attr('action'),
beforeSend: function() {
//alert('Подождите');
//показываем загрузку если она нужна
//можем выключать кнопку отправки
},
success: function(data) {
if (data == 1){
form.children('.alert').removeClass('danger').addClass('success').html(success);
}
else {
form.children('.alert').removeClass('success').addClass('danger').html(data.errors);
}
}
});
e.preventDefault();
});
$data = ['errors' => 'сюда пишите ошибку'];
return json_encode($data);
Did the asp.net mvc tag confuse you?
OK. Then tell me how to get the partial view markup string in the controller...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question