Good day everyone. I am trying to send an AJAX form to the server, but the controller's method with which the form is to be processed is not called. Server 500 failed to respond. Here is the form code:

@Scripts.Render("~/Scripts/jquery-3.3.1.min.js") @Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.min.js") @Scripts.Render("~/Scripts/jquery.unobtrusive-ajax.js") @using (Ajax.BeginForm("PhotoSessionInfo", new AjaxOptions { UpdateTargetId = "generalPhotoPos", LoadingElementId = "loading-spin" })) { <span>Название фотосесии (будет отображаться в галереи): </span> <br /> @Html.TextBox("sessionName", null, new { @class = "sessionName" }) <br /> <br /> <span>Выберите изображение, которое будет являться заставкой фотосесии: </span> <br /> <input type="file" name="generalPhoto" accept=".jpg, .jpeg, .png"> <br /> <br /> <span>Выберите изображения: </span> <br /> <input type="file" name="photos" accept=".jpg, .jpeg, .png"> <button type="submit"> Отправить </button> } <div id="generalPhotoPos"> <img src="~/Content/loading-spin.svg" id="loading-spin" /> </div> 

Here is the code for the PhotoSessionInfo method:

  [HttpPost] public ActionResult PhotoSessionInfo(HttpPostedFile generalPhoto, string sessionName, HttpPostedFile[] photos) { long generalPhotoSize = new System.IO.FileInfo(generalPhoto.ToString()).Length; string[] photoNames = new string[photos.Length]; for (int photo = 0; photo<= photos.Length; photo++ ) { //Если данные больше 2мб, то возвражается представление с сообщением об ошибке long size = new System.IO.FileInfo(photo.ToString()).Length; if (size > 2000000 && photos.Length ==0) { return PartialView("Error"); } photoNames[photo] = System.IO.Path.GetFileName(photos[photo].FileName); } string [] photoURLs = new string[photos.Length]; for(int i =0; i<=photoNames.Length; i++) { //Сохраняю фотографии в папку на сервере, после чего записываю в массив путь к этой фотографии photos[i].SaveAs(Server.MapPath("~/images/Photos/" + photoNames[i])); photoURLs[i] = "~/images/Photos/" + photoNames[i]; } string generalPhotoURL = null; if (generalPhoto != null && generalPhotoSize > 2000000) { string generalPhotoName = System.IO.Path.GetFileName(generalPhoto.FileName); generalPhoto.SaveAs(Server.MapPath("~/images/GeneralPhotos/" + generalPhotoName)); generalPhotoURL = "~/images/GeneralPhotos/" + generalPhotoName; } else { return PartialView("Error"); } string imgURLs = null; for(int i = 0; i <= photoURLs.Length; i++) { imgURLs += photoURLs[i] + "," + " "; } return PartialView(); } 

Here is the code for the created form:

 <form action="/Home/PhotoSessionInfo" data-ajax="true" data-ajax-loading="#loading-spin" data-ajax-mode="replace" data-ajax-update="#generalPhotoPos" id="form0" method="post">... </form> 

When you click the "Send" button in the browser console, you receive several error messages:

And such an error appears in Visual Studio enter image description here

Here is the answer:

 <html> <head> <title>Для данного объекта не определено беспараметрических конструкторов.</title> <meta name="viewport" content="width=device-width" /> <style> body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px} b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px} H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red } H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon } pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt} .marker {font-weight: bold; color: black;text-decoration: none;} .version {color: gray;} .error {margin-bottom: 10px;} .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; } @media screen and (max-width: 639px) { pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; } } @media screen and (max-width: 479px) { pre { width: 280px; } } </style> </head> <body bgcolor="white"> <span><H1>Ошибка сервера в приложении '/'.<hr width=100% size=1 color=silver></H1> <h2> <i>Для данного объекта не определено беспараметрических конструкторов.</i> </h2></span> <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif "> <b> Описание: </b>Необработанное исключение при выполнении текущего веб-запроса. Изучите трассировку стека для получения дополнительных сведений о данной ошибке и о вызвавшем ее фрагменте кода. <br><br> <b> Сведения об исключении: </b>System.MissingMethodException: Для данного объекта не определено беспараметрических конструкторов.<br><br> <b>Ошибка источника:</b> <br><br> <table width=100% bgcolor="#ffffcc"> <tr> <td> <code> 

An unhandled exception occurred during the execution of the current web request. Information on the origin and location of the exception can be obtained using the following exception stack trace.

  </td> </tr> </table> <br> <b>Трассировка стека:</b> <br><br> <table width=100% bgcolor="#ffffcc"> <tr> <td> <code><pre> 

[MissingMethodException: Non-parametric constructors are not defined for this object.]

Here is the header information: General :

Request URL: http: // localhost: 55488 / Home / PhotoSessionInfo

Request Method: POST

Status Code: 500 Internal Server Error

Remote Address: [:: 1]: 55488

Referrer Policy: no-referrer-when-downgrade

Response Headers :

Cache-Control: private

Content-Length: 12631

Content-Type: text / html; charset = utf-8

Date: Sat, 04 Aug 2018 11:31:34 GMT

Server: Microsoft-IIS / 10.0

X-AspNet-Version: 4.0.30319

X-Powered-By: ASP.NET

X-sourcefiles: =? Utf-8? B?

Request Headers:

Accept: /

Accept-Encoding: gzip, deflate, br

Accept-Language: ru-RU, ru; q = 0.9, en-US; q = 0.8, en; q = 0.7

Connection: keep-alive

Content-Length: 48

Content-Type: application / x-www-form-urlencoded; charset = UTF-8

Host: localhost: 55488

Origin: http: // localhost: 55488

Referer: http: // localhost: 55488 / Home / DataCheck

User-Agent: Mozilla / 5.0 (Windows NT 10.0; Win64; x64) AppleWebKit / 537.36 (KHTML, like Gecko) Chrome / 68.0.3440.75 Safari / 537.36

X-Requested-With: XMLHttpRequest

Fprm Data :

sessionName: Alex

X-Requested-With: XMLHttpRequest

Here is the entire controller code, as requested. I commented out a lot, since most of the code of the PhotoSessionInfo method does not affect anything:

  public class HomeController : Controller { public ActionResult Index() { return View("Index"); } [HttpPost] public ActionResult DataCheck (string adminlogin, string adminpassword) { if(adminlogin == "Kate_adm" && adminpassword == "1234520") { return View("Admin_Page"); } else { ViewBag.Text = "Неверно введены данные."; return View("Index"); } } [HttpPost] public PartialViewResult PhotoSessionInfo (HttpPostedFile generalPhoto, string sessionName, HttpPostedFile photos) { long generalPhotoSize = new System.IO.FileInfo(generalPhoto.ToString()).Length; //string[] photoNames = new string[photos.Length]; //for (int photo = 0; photo<= photos.Length; photo++ ) //{ // //Если данные больше 2мб, то возвражается представление с сообщением об ошибке // long size = new System.IO.FileInfo(photo.ToString()).Length; // if (size > 2000000 && photos.Length ==0) // { // return PartialView("Error"); // } // photoNames[photo] = System.IO.Path.GetFileName(photos[photo].FileName); //} //string [] photoURLs = new string[photos.Length]; //for(int i =0; i<=photoNames.Length; i++) //{ // //Сохраняю фотографии в папку на сервере, после чего записываю в массив путь к этой фотографии // photos[i].SaveAs(Server.MapPath("~/images/Photos/" + photoNames[i])); // photoURLs[i] = "~/images/Photos/" + photoNames[i]; //} //string generalPhotoURL = null; //if (generalPhoto != null && generalPhotoSize > 2000000) //{ // string generalPhotoName = System.IO.Path.GetFileName(generalPhoto.FileName); // generalPhoto.SaveAs(Server.MapPath("~/images/GeneralPhotos/" + generalPhotoName)); // generalPhotoURL = "~/images/GeneralPhotos/" + generalPhotoName; //} //else //{ // return PartialView("Error"); //} //string imgURLs = null; //for(int i = 0; i <= photoURLs.Length; i++) //{ // imgURLs += photoURLs[i] + "," + " "; //} return PartialView(); } 
  • Why is this HttpPostedFile[] photos array? Judging by the markup, this is also one file. Maybe ASP.NET could not get 1 file from the file to the array of parameters? - tym32167
  • Just changed the array to “one file”, but unfortunately, the result is the same - Lev Kostychenko
  • one
    In chrome there is a network tab - there should be this request with 500 and in the response body there should be a stack trace. Bring her text here (text, not a picture) - tym32167
  • Added all data about requests - Lev Kostychenko
  • Show the controller constructor? Does he have parameters? - tym32167

0