Почему не связывается модель JSON ASP.NET MVC Core
На Action методе не происходит связка модели. Ни в каком варианте Код Action
public ContentResult Message([FromBody] MessageModel form)
{
if (ModelState.IsValid)
{
Db.MessagesCV.Add(new MessagesCV
{
Contact = form.Contact,
DateTime = DateTime.Now,
Message = form.Message,
Id = Guid.NewGuid(),
Name = form.Name,
IP = HttpContext.Connection.RemoteIpAddress.ToString()
});
Db.SaveChanges();
return Content("Спасибо! Свяжусь с Вами в ближайшее время");
}
return Content("Неправильно заполнена форма связи");
}
Настройки приложения
public static void Main(string[] args)
{
var builder = WebApplication.CreateBuilder(args);
var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString, b => b.MigrationsAssembly("Web")).UseLazyLoadingProxies()/*, contextLifetime: ServiceLifetime.Transient*/);
builder.Services.AddMvc().AddNewtonsoftJson(options =>
{
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
});
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseMiddleware<AccessLogMiddleware>();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}").RequireHost("p.site", "www.p.site", "localhost");
app.MapControllerRoute(
name: "cv",
pattern: "{controller=CV}/{action=Index}/{id?}").RequireHost("cv.p.site", "www.cv.p.site", "localhost");
app.MapControllerRoute(
name: "admin",
pattern: "{controller=Admin}/{action=Index}/{id?}").RequireHost("admin.p.site", "www.admin.p.site", "localhost");
app.MapRazorPages();
app.Run();
}
Модель
[BindProperties]
public class MessageModel
{
[Required]
[MaxLength(500)]
public string Message { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
[Required]
[MaxLength(50)]
public string Contact { get; set; }
}
JS
$("#sendMessageCv").on('click', function () {
var messageModel = new Object();
messageModel.Message = $("textarea[name='Message']").val();
messageModel.Name = $("input[name='Name']").val();
messageModel.Contact = $("input[name='Contact']").val();
$.ajax({
url: 'CV/Message',
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(messageModel),
//data: { Message: $("textarea[name='Message']").val(), Name: $("input[name='Name']").val(), Contact : $("input[name='Contact']").val() },
success: function (data) {
alert(data);
}
});
});
Пробовал передавать как JSON, пробовал простую передачу данных без [FromBody] со скриптом JS
$("#sendMessageCv").on('click', function () {
$.ajax({
url: 'CV/Message',
type: "POST",
data: { Message: $("textarea[name='Message']").val(), Name: $("input[name='Name']").val(), Contact : $("input[name='Contact']").val() },
success: function (data) {
alert(data);
}
});
});
Ничего не помогает. В DevTools вижу что данные передаются, но с моделью они не связываются
public ContentResult Message(string Message, string Name, string Contact)
В таком виде тоже ничего не приходит
Источник: Stack Overflow на русском