Quantcast
Channel: How to make array values readable into C# MVC controller - Stack Overflow
Viewing all articles
Browse latest Browse all 2

How to make array values readable into C# MVC controller

$
0
0

I have specific input fields with array values, but when I passed it into my controller that specific fields don't have any values only [objects], but when I output in into a console.log all the values are in there. here are my codes

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) {
        });
    });

controller

[![\[HttpPost\]
        public ActionResult AddPackage(TourPackage package)
        {

            if (ModelState.IsValid)
            {

            }
            return View();
        }

MY form screenshot

controller output

here is my model

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; }
    }

I try both of the answers below, but still not working (array variables show only [objects])

Question Update

How to insert array or list value or it is possible to insert an array or list values example dates array values.

Here is my controller this is not binded to my model

 [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!");
            }
        }

my javascripts

data mapping

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()
            );
        });
    }

submit script

$("#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'
        });
    });

data receive to my controler

enter image description here

database structures

 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)
);

my query class

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*/
        }
    }

my connect class I don't have any code for adding package in my Connect class because I don't know how to do it.

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();
            }
        }
    }

updated add package form ui

enter image description here


Viewing all articles
Browse latest Browse all 2

Latest Images

Trending Articles





Latest Images