Я пытаюсь отправить зарегистрированную информацию о продаже велосипеда. Когда я нажимаю кнопку «Отправить», форма не отпC#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Я пытаюсь отправить зарегистрированную информацию о продаже велосипеда. Когда я нажимаю кнопку «Отправить», форма не отп

Сообщение Anonymous »

Действие в BicycleController
public ActionResult SellerAddPage()
{
var model = new BikeModel();
return View(model);
}
[HttpPost]
public ActionResult SellerAddPage(BikeModel bicycle, HttpPostedFileBase Image)
{
try
{
// Save image to folder
if (Image != null && Image.ContentLength > 0)
{
var fileName = Path.GetFileName(Image.FileName);
var path = Path.Combine(Server.MapPath("~/Content/Image"), fileName);
Image.SaveAs(path);
bicycle.Image = "/Content/Images/" + fileName; // Save the relative path in the database
}

int? userId = Session["UserId"] as int?;
if (userId == null)
{
// Handle case where UserId is not in session (user not logged in or session expired)
ViewBag.ErrorMessage = "User is not logged in.";
return View(bicycle);
}
else
{
bicycle.UserID = userId.Value;
// Save bicycle details to the database
using (var connection = new SqlConnection(connectionString))
{
string query = "INSERT INTO [sales].[bicycle] (user_id,brand_name, category_name, description, picture) VALUES (@user_id,@brand_name, @category_name, @description, @picture)";
SqlCommand cmd = new SqlCommand(query, connection);
cmd.Parameters.AddWithValue("@user_id", bicycle.UserID);
cmd.Parameters.AddWithValue("@brand_name", bicycle.Brand);
cmd.Parameters.AddWithValue("@category_name", bicycle.Category);
cmd.Parameters.AddWithValue("@description", bicycle.Description);
cmd.Parameters.AddWithValue("@picture", bicycle.Image);

connection.Open();
cmd.ExecuteNonQuery();
}
ViewBag.Message = "Bicycle uploaded successfully.";
return RedirectToAction("SellerPage");

}
}
catch (Exception ex)
{
ViewBag.ErrorMessage = "An error occurred while adding the bicycle: " + ex.Message;
}
return View("SellerPage");
}

Model

public class BikeModel
{
[Required]
public int UserID { get; set; }
public int BicycleID { get; set; }
[Required]
public string Brand { get; set; }
public List ListBrand { get; set; }
[Required]
public string Category { get; set; }
public List ListCategory { get; set; }
[Required]
public string Description { get; set; }
[Required]
public string Image { get; set; }
public BikeModel()
{
ListBrand = new List
{
new SelectListItem{Value="Electra",Text="Electra"},
new SelectListItem{Value="Haro",Text="Haro"},
new SelectListItem{Value="Heller", Text = "Heller"},
new SelectListItem{Value="Pure Cycles", Text = "Pure Cycles"},
new SelectListItem{Value="Ritchey", Text = "Ritchey"},
new SelectListItem{Value="Strider", Text = "Strider"},
new SelectListItem{Value="Sun Bicycles", Text = "Sun Bicycles"},
new SelectListItem{Value="Surly", Text = "Surly"},
new SelectListItem{Value="Trek", Text = "Trek"},

};
ListCategory = new List
{
new SelectListItem{Value="Children Bicycles", Text = "Children Bicycles"},
new SelectListItem{Value="Comfort Bicycles", Text = "Comfort Bicycles"},
new SelectListItem{Value="Cruisers Bicycles", Text = "Cruisers Bicycles"},
new SelectListItem{Value="Cyclocross Bicycles", Text = "Cyclocross Bicycles"},
new SelectListItem{Value="Electric Bikes", Text = "Electric Bikes"},
new SelectListItem{Value="Mountain Bikes", Text = "Mountain Bikes"},
new SelectListItem{Value="Road Bikes", Text = "Road Bikes"},
};

}```

here is myView
@model u23704137_HW02.Models.BikeModel
@{

ViewBag.Title = "SellerAddPage";
}
@using (Html.BeginForm("SellerAddPage", "Bicycle", FormMethod.Post, new { enctype = "multipart/form-data" }))

{
@Html.AntiForgeryToken()

BicycleModel

@Html.ValidationSummary(true, "", new { @class = "text-danger" })

@Html.LabelFor(model => model.Brand, htmlAttributes: new { @class = "control-label col-md-2" })

@Html.EditorFor(model => model.Brand, new { htmlAttributes = new { @class = "form-control",@id="brandId" } })
@Html.ValidationMessageFor(model => model.Brand, "", new { @class = "text-danger" })



@Html.LabelFor(model => model.Category, htmlAttributes: new { @class = "control-label col-md-2" })

@Html.EditorFor(model => model.Category, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Category, "", new { @class = "text- danger" })



@Html.LabelFor(model => model.Description, htmlAttributes: new { @class = "control-label col-md-2" })

@Html.EditorFor(model => model.Description, new { htmlAttributes = new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Description, "", new { @class = "text- danger" })



@Html.LabelFor(model => model.Image, htmlAttributes: new { @class = "control-label col-md-2" })

@Html.EditorFor(m => m.Image,new {htmlAttributes=new { @class = "form-control" } })
@Html.ValidationMessageFor(model => model.Image, "", new { @class = "text-danger" })









}``
Я пробовал использовать множество вещей, включая метод get, но не могу отправить форму, и большинство решений относилось к asp. net core, и я работаю над .net framework. Я также попытался воссоздать проект и добавить обработку исключений в метод http post.


Подробнее здесь: https://stackoverflow.com/questions/790 ... e-when-i-c
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «C#»