如何使数组值在 C# MVC 控制器中可读
Posted
技术标签:
【中文标题】如何使数组值在 C# MVC 控制器中可读【英文标题】:How to make array values readable into C# MVC controller 【发布时间】:2020-01-27 15:05:57 【问题描述】:我有带有数组值的特定输入字段,但是当我将它传递到我的控制器时,特定字段没有任何值只有 [objects],但是当我输出到 console.log 时,所有值都在那里.这是我的代码
function fLDetails()
flIntinerary = $("[name='Itinerary']").map(function ()
return
itinerayTitle: $(this).find("input[name='ItineraryTitle']").val(),
itinerayDes: $(this).find("textarea[name='ItineraryDes']").val()
;
);
$("#primaryItineraryName").val(flIntinerary);
$("#btnPackageSave").click(function (e)
e.preventDefault(e);
fLDetails();
var packageForm = $("#packageForm");
if (!packageForm.valid())
return false;
var url = packageForm.attr("action");
var fromData = packageForm.serialize();
$.post(url, fromData, function (data)
);
);
控制器
[![\[HttpPost\]
public ActionResult AddPackage(TourPackage package)
if (ModelState.IsValid)
return View();
这是我的模型
public class TourPackage
[Display(Name = "Package name")]
[Required(ErrorMessage = "Please enter package name!")]
public string p_name get; set;
[Display(Name = "Package price")]
[Required(ErrorMessage = "Please enter package price")]
public string p_price get; set;
[Display(Name = "Travel Date(s)")]
[Required(ErrorMessage = "Please select a travel date(s)!")]
public List<DateTime> p_traveldate get; set;
[Display(Name = "Bedroom type")]
[Required(ErrorMessage = "Please select a Bedroom type")]
public string p_bedroom get; set;
[Display(Name = "Flight details")]
[Required(ErrorMessage = "Please enter flight details")]
public List<string> p_flghtdetails get; set;
[Display(Name = "Inclusions")]
[Required(ErrorMessage = "Please enter exclusion(s)")]
public List<string> p_inclusion get; set;
[Display(Name = "Itinerary")]
[Required(ErrorMessage = "Please enter itinerary name!")]
public List<string> p_itineraryName get; set;
[Display(Name = "Itinerary description")]
[Required(ErrorMessage = "Please enter itinerary description!")]
public string p_itineraryDescription get; set;
[Display(Name = "Terms and Conditions")]
[Required(ErrorMessage = "Please enter terms and conditions!")]
public string p_termCondition get; set;
[Display(Name = "Exclusion")]
[Required(ErrorMessage = "Please enter exclusion!")]
public string p_exclusion get; set;
[Display(Name = "Header image")]
public string p_imgHeader get; set;
[Display(Name = "Image slides")]
[Required(ErrorMessage = "Please select an image!")]
public string p_imgSlide get; set;
我尝试了以下两个答案,但仍然无法正常工作(数组变量仅显示 [objects])
问题更新
如何插入数组或列表值,或者可以插入数组或列表值,例如日期数组值。
这是我的控制器,它没有绑定到我的模型
[HttpPost]
public ActionResult SavePackage(string p_name, string p_price, int p_bedroom, List<string> p_traveldate, List<string> p_flghtdetails, List<string> p_inclusion,
List<string> ItineraryName, List<string> p_termCondition, List<string> p_exclusion)
if (ModelState.IsValid)
try
//int packageData = AddPackageDatails(p_name, p_price, p_bedroom, p_traveldate, p_flghtdetails, p_inclusion, ItineraryName, p_termCondition, p_exclusion);
return Content("sasasas");
catch (Exception e)
return Content("Error: " + e.Message);
else
return Content("Failed to saved Package details!");
我的 javascripts
数据映射
var flDetails = [];
var flInclusion = [];
var flIntinerary = [];
var flTermsCon = [];
var flExclusion = [];
var travelDateArray = [];
function fLDetails()
$("input[name=flightDetails]").each(function ()
flDetails.push($(this).val());
);
$("input[name=inclusion]").each(function ()
flInclusion.push($(this).val());
);
$("input[name=termCondition]").each(function ()
flTermsCon.push($(this).val());
);
$("input[name=exclusion]").each(function ()
flExclusion.push($(this).val());
);
$("[name='divArray']").map(function ()
travelDateArray.push(
$(this).find("input[name='fromtDate']").val() + " | " +
$(this).find("input[name='toDate']").val()
);
);
$("[name='Itinerary']").map(function ()
flIntinerary.push(
$(this).find("input[name='ItineraryTitle']").val() + " | " +
$(this).find("textarea[name='ItineraryDes']").val()
);
);
提交脚本
$("#btnPackageSave").click(function (e)
e.preventDefault(e);
fLDetails();
var packageForm = $("#packageForm");
if (!packageForm.valid())
return false;
//var _url = packageForm.attr("action");
var p_name = $("#packageName").val();
var p_price = $("#packagePrice").val();
var p_bedroom = $("#_bedroom").val();
var data1 = JSON.stringify( "p_name": p_name, "p_price": p_price, "p_bedroom": p_bedroom, "p_flghtdetails": flDetails, "p_inclusion": flInclusion, "ItineraryName": flIntinerary, "p_termCondition": flTermsCon, "p_exclusion": flExclusion, "p_traveldate": travelDateArray);
$.ajax(
type: "POST",
url: "/ControlPanel/SavePackage",
data: data1,
dataType: "json",
traditional: true,
contentType: 'application/json'
);
);
数据接收到我的控制器
数据库结构
create database traveldb;
create table bedrooms (
bed_id int primary key identity(1,1) not null,
bedtype varchar(50) not null
);
create table t_package (
p_id int primary key identity(1,1) not null,
p_name varchar(100) not null,
p_price float not null,
p_bedroom int,
foreign key(p_bedroom)references bedrooms(bed_id),
p_inclusion text,
p_termsandCon text,
p_exclusion text,
p_flightdetails text
);
create table itinerary (
iti_id int primary key identity(1,1) not null,
iti_name varchar(50) not null,
iti_description text not null,
packageId int,
foreign key (packageId) references t_package(p_id)
);
create table travel_dates (
tdateId int primary key identity(1,1) not null,
dateFrom date not null,
dateTo date not null,
packageId int,
foreign key(packageId) references t_package(p_id)
);
create table tble_img (
imd_id int primary key identity(1,1) not null,
img_header varchar(150),
img_slide varchar(1000),
packageId int,
foreign key (packageId) references t_package(p_id)
);
我的查询类
public static class Query
public static int AddBedroom(string bedtype)
Bedtype BedType = new Bedtype
bedtype = bedtype
;
string sql = @"insert into dbo.bedrooms (bedtype) values (@bedtype);";
return Connection.Connect.SaveBedType<Bedtype>(sql, BedType);
public static List<Bedtype> bedtypeData()
string sql = @"select * from dbo.bedrooms;";
return Connection.Connect.LoadData<Bedtype>(sql);
public static int AddPackageDatails(string name, string price, int bedroom, List<string> dates, List<string> flightdetails, List<string> inclusion, List<string> itinerary, List<string> conditions,
List<string> exclusion)
TourPackage package = new TourPackage
p_name = name,
p_price = price,
p_bedroom = bedroom,
;
/* here is my problem how to insert list values or array values or it is possible to do that? into multiple table*/
我的连接类 我没有任何用于在我的 Connect 类中添加包的代码,因为我不知道该怎么做。
public class Connect
public static string GetConnectionString(string connection = "mycon")
return ConfigurationManager.ConnectionStrings[connection].ConnectionString;
public static int SaveBedType<B>(string sql, B data)
using (IDbConnection con = new SqlConnection(GetConnectionString()))
return con.Execute(sql, data);
public static List<B> LoadData<B>(string sql)
using (IDbConnection con = new SqlConnection(GetConnectionString()))
return con.Query<B>(sql).ToList();
更新了添加包表单ui
【问题讨论】:
【参考方案1】:每次单击按钮时,您都将值添加到数组中:
假设所有的数组值都在flIntinerary
var postData = values: flIntinerary;
因此通过 ajax 传递 postData
那么你的模型一定是这样的
public TourPackage
public list<string> values get; set;
和控制器是这样的:
public ActionResult AddPackage(TourPackage postData)
if (ModelState.IsValid)
return View();
【讨论】:
谢谢你们俩,但你们的两个答案都不起作用。 并非所有字段都有数组值,有些输入字段没有数组值,以上是关于如何使数组值在 C# MVC 控制器中可读的主要内容,如果未能解决你的问题,请参考以下文章