Fetch all files of local directory and populate files names in dropdownlist
2 Answers 28 Views
Wassim
Top achievements
Rank 1
Iron
Wassim asked on 31 May 2021, 03:42 PM

Hello, 

I want to Fetch all files in a local Folder (Directory) and populate file names and present them in my view page as a drop down list.

taking the name of the file selected and save it in my table as a string value.

any suggestions please ?

Thank you in advance.

2 Answers, 1 is accepted

Sort by
0
Ivan Danchev
Telerik team
answered on 03 Jun 2021, 10:04 AM

Hello Wassim,

With regard to getting the files from a folder, we would recommend checking the solutions suggested in stackoverflow, for example: https://stackoverflow.com/questions/4254339/how-to-loop-through-all-the-files-in-a-directory-in-c-net

As for populating the DropDownList with the file names, once you have them on the server, you can use a view model with a field that will hold the file name, then create a collection of that view model. You can then use either local data binding or remote binding to bind the the DropDownList, as demonstrated in this documentation article: https://docs.telerik.com/aspnet-mvc/html-helpers/editors/dropdownlist/binding/model-binding

Regards,
Ivan Danchev
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

Thank you for replying Ivan,

I just created a multiselect field like this.




@model mySolution.Models.myModel

@using (Html.BeginForm("AddOptions", "myController", FormMethod.Post))

{
@Html.AntiForgeryToken()

<div class="form-group">
<div class="form-row">
@Html.LabelFor(model => model.OPTION_CODE, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-8">
@(Html.Kendo().MultiSelectFor(model => model.OPTION_CODE)
.Name("OPTION_CODE")
.DataTextField("ID_OPTION")
.DataValueField("LABEL_OPTION")
.HtmlAttributes(new { style = "width:100%" })
.AutoBind(false)
.DataSource(source =>
{
source.Custom()
.ServerFiltering(true)
.ServerPaging(true)
.PageSize(80)
.Type("aspnetmvc-ajax")
.Transport(transport =>
{
transport.Read("Options_Read", "DDLController");
})
.Schema(schema =>
{
schema.Data("Data")
.Total("Total");
});
})
)
</div>
</div>
</div>

<div class="form-group">
<div class="form-row">
<div class="col-md-12" style="text-align: right;">
@Html.ActionLink("Cancel", "myView", "myController", null, new { @class = "mr-1 mb-1 btn btn-secondary" })
<input type="submit"value="Save"class="mr-1 mb-1 btn btn-primary" />
</div>
</div>
</div>
}



my model


namespace mySolution.Models
{
public class myModel
{
public int myModelodel_PK_ID { get; set; }

[Required(ErrorMessage = "You must select option.")]
public string OPTION_CODE { get; set; }


}
}



my adding method is like this, it calls a web api service that execute a stored procedure to do the save in my table



public async Task<ActionResult> AddOptions(myModel model)
{

using (var client = new HttpClient(new LoggingHandler(new HttpClientHandler())))
{
client.BaseAddress = new Uri(AppSetting.AppPath);

var result = await client.PostAsJsonAsync("api/MyApiController", model);

if (result.IsSuccessStatusCode)
{

return RedirectToAction("myView");
}
else
{
ModelState.AddModelError(string.Empty, "Server error try after some time.");
}
}
return View();
}
how I will be able to save the list of selected options in my sql table / same thing for modification; any suggestions or help will be much appreciated ?
- by
Wassim
Top achievements
Rank 1
Iron
on 04 Jun 2021, 11:19 AM
0
Wassim
Top achievements
Rank 1
Iron
answered on 04 Jun 2021, 11:17 AM

Thank you for replying Ivan,

I just created a multiselect field like this.

 

 

@model mySolution.Models.myModel

@using (Html.BeginForm("AddOptions", "myController", FormMethod.Post)) { @Html.AntiForgeryToken() <div class="form-group"> <div class="form-row"> @Html.LabelFor(model => model.OPTION_CODE, htmlAttributes: new { @class = "control-label col-md-4" }) <div class="col-md-8"> @(Html.Kendo().MultiSelectFor(model => model.OPTION_CODE) .Name("OPTION_CODE") .DataTextField("ID_OPTION") .DataValueField("LABEL_OPTION") .HtmlAttributes(new { style = "width:100%" }) .AutoBind(false) .DataSource(source => { source.Custom() .ServerFiltering(true) .ServerPaging(true) .PageSize(80) .Type("aspnetmvc-ajax") .Transport(transport => { transport.Read("Options_Read", "DDLController"); }) .Schema(schema => { schema.Data("Data") .Total("Total"); }); }) ) </div> </div> </div> <div class="form-group"> <div class="form-row"> <div class="col-md-12" style="text-align: right;"> @Html.ActionLink("Cancel", "myView", "myController", null, new { @class = "mr-1 mb-1 btn btn-secondary" }) <input type="submit"value="Save"class="mr-1 mb-1 btn btn-primary" /> </div> </div> </div> }


my model 


namespace mySolution.Models
{
    public class myModel
    {
        public int myModelodel_PK_ID { get; set; }
       
        [Required(ErrorMessage = "You must select option.")]
        public string OPTION_CODE { get; set; }
     

    }
}


my adding method is like this, it calls a web api service that execute a stored procedure to do the save in my table 

 

        public async Task<ActionResult> AddOptions(myModel model)
        {

            using (var client = new HttpClient(new LoggingHandler(new HttpClientHandler())))
            {
                client.BaseAddress = new Uri(AppSetting.AppPath);

                var result = await client.PostAsJsonAsync("api/MyApiController", model);
               
                if (result.IsSuccessStatusCode)
                {
                   
                    return RedirectToAction("myView");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Server error try after some time.");
                }
            }
            return View();
        }
how I will be able to save the list of selected options in my sql table / same thing for modification; any suggestions or help will be much appreciated ?
Hi Wassim, are you planning to save only the files names and the path or you want to save the files into sql database as byte array?
- by
Tony
Top achievements
Rank 1
Iron
Iron
Iron
on 07 Jun 2021, 07:38 AM
Hi Tony, for this step, I would like to save the name of the different options selected (multiselected) into a coloumn of my sql table because I can have multiple choices to select and send it.
- by
Wassim
Top achievements
Rank 1
Iron
on 07 Jun 2021, 07:46 AM
Hi Wassim, i dont see anything wrong with the way you have the setup for post to the addoption method. what happens when you click submit? do you see the model being populated with the OPTION_CODEs.?
- by
Tony
Top achievements
Rank 1
Iron
Iron
Iron
on 07 Jun 2021, 01:37 PM | edited
Hi Tony,
the concern that I have is the fact of registering multiple values when making multiple choices from my multiselect field.. I manage to register only one value in my table not multiple values (any javascript function to make so i can split them so i can save many values)
the 2nd problem, when I try to modify an element ... I cannot recover the good recorded elements !

Any help please ?
- by
Wassim
Top achievements
Rank 1
Iron
on 07 Jun 2021, 02:24 PM
Hi Wassim, how about trying to make your field model to a list public List<string> OPTION_CODE { get; set; }. on the back end in your service. you should be able to read this field. i have not tested this give it a try. as to the modification part can you post the html part for modification. this should be a custom template i assume.
- by
Tony
Top achievements
Rank 1
Iron
Iron
Iron
on 07 Jun 2021, 02:36 PM
Hi Tony,
Yes, I already thought about that ... as soon as you access the list screen when you retrieve the list of items. An error is displayed:
Could not cast or convert from System.String to System.Collections.Generic.List`1 [System.String].
as well as the recording does not work
maybe I will need to use a js function and split selected options by ',' ?

Compared to the modification .. nothing special, I created a service that retrieves the values of different fields

<div class="form-group">
<div class="form-row">
@Html.LabelFor(model => model.AUTOMATES_CO_OPTION, htmlAttributes: new { @class = "control-label col-md-4" })
<div class="col-md-8">
@(Html.Kendo().MultiSelectFor(model => model.AUTOMATES_CO_OPTION)
.Name("AUTOMATES_CO_OPTION")
.DataTextField("DDL_OPTION_CIP")
.DataValueField("DDL_OPTION_CIP")
.HtmlAttributes(new { style = "width:100%" })
.AutoBind(false)
.DataSource(source =>
{
source.Custom()
.ServerFiltering(true)
.ServerPaging(true)
.PageSize(80)
.Type("aspnetmvc-ajax")
.Transport(transport =>
{
transport.Read("OptionsCIPDDL_Read", "Preparation");
})
.Schema(schema =>
{
schema.Data("Data")
.Total("Total");
});
})
)
</div>
</div>
</div>
- by
Wassim
Top achievements
Rank 1
Iron
on 07 Jun 2021, 04:59 PM
Hi Wassim, where is the error displayed?

you could keep your control as simple like this it should work. and then add other features to the control once all is working as expected. the below works with no problem on my side.


model
public class myModel
{
public int myModelodel_PK_ID { get; set; }

[Required(ErrorMessage = "You must select option.")]
public List<string> OptionCodeList { get; set; }


}


@(Html.Kendo().MultiSelectFor(model => model.OptionCodeList )
.Name("OPTION_CODE")
.DataTextField("LABEL_OPTION")
.DataValueField("ID_OPTION")
.HtmlAttributes(new { style = "width: 485px;" })
.IgnoreCase(true)
.AutoBind(false)
.ValuePrimitive(false)
.Filter(FilterType.Contains)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("Options_Read", "DDLController");
})
.ServerFiltering(true);
})
)
- by
Tony
Top achievements
Rank 1
Iron
Iron
Iron
on 07 Jun 2021, 07:11 PM
Hi Tony,
the cause of using this component like that because i'm using DataSourceRequest instance in DDLController to fetch the options from my database.

changing the type of "OptionCode" from string to List<string> show me the error when I access the list display screen and exactly in my web api controller :

public class MyApiController: ApiController
{
public IEnumerable<myModel> Get()
{
myDBEntities db = new myDBEntities ();

string json = string.Concat(db.Database.SqlQuery<string>("exec Proc_List"));
var results = JsonConvert.DeserializeObject<IList<myModel>>(json); //the error is displayed in this line
//Newtonsoft.Json.JsonSerializationException : 'Error converting value "acknowledgeReceipt" to type //'System.Collections.Generic.List`1[System.String]'. Path '[1].OPTION_CODE ', line 1, position 636.'
//ArgumentException : Could not cast or convert from System.String to //System.Collections.Generic.List`1[System.String].

if (results == null)
return new List<myModel>();
else
return results.ToList();

}

public IHttpActionResult Post([FromBody] myModel mymodel)
{
myDBEntities db = new myDBEntities ();

SqlParameter returnCode = new SqlParameter("@ReturnCode", SqlDbType.Int);
returnCode.Direction = ParameterDirection.Output;

try
{

var st = db.Database.ExecuteSqlCommand("exec Proc_Add_Option @CoOption",
new SqlParameter("@CoOption", mymodel.OPTION_CODE ) , returnCode);

}
catch (SqlException ex)
{
Log.Fatal(ex.Message);
return BadRequest(ex.Message);
}

return Ok();
}
}

public class myModel
{
public int myModelodel_PK_ID { get; set; }

public string OPTION_CODE { get; set; }


}
- by
Wassim
Top achievements
Rank 1
Iron
on 08 Jun 2021, 08:02 AM
Hi Wassim,

these two lines of code

string json = string.Concat(db.Database.SqlQuery<string>("exec Proc_List"));
are you sure it will return json data? string.concat method will add more values to the string

try something like this below

var result = db.Database.SqlQuery<myModel>("Proc_List");

remove this line
var results = JsonConvert.DeserializeObject<IList<myModel>>(json);

return your result

your get method will look like this now

public mymodel getoptionscodes()
{
var result = db.Database.SqlQuery<myModel>("Proc_List");
return result ;
}

then you call your method like this

myModel mymodel = getoptionscodes();
- by
Tony
Top achievements
Rank 1
Iron
Iron
Iron
on 08 Jun 2021, 10:05 AM
Hi Tony, unfortunately, that is not what I am looking for. my stored procedure (web api) does return a response in json format.
I work with this in my entire solution.
I can't seem to send multiselected values and save in my sql table.
- by
Wassim
Top achievements
Rank 1
Iron
on 08 Jun 2021, 05:01 PM | edited
Hi Wassim,

have a look at this thread https://www.telerik.com/forums/multiselect-does-not-send-data-to-controller-method.

its almost the same as what you are doing.

@using (Html.BeginForm("Save", "Home"))
{
<div class="form-group">
@(Html.TextBoxFor(model => model.ParentID))
</div>

<div class="form-group">
<div class="col-md-8">
@(Html.Kendo().MultiSelectFor(model => model.RolesList)
.Placeholder("Select roles")
.DataTextField("Name")
.DataValueField("Id")
.HtmlAttributes(new { style = "width: 485px;" })
.IgnoreCase(true)
.AutoBind(true)
.ValuePrimitive(false)
.Filter(FilterType.Contains)
.DataSource(source =>
{
source.Read(read =>
{
read.Action("GetRoles", "Home");
})
.ServerFiltering(true);
})
)
</div>
</div>

<input type="submit" value="Save" />

as for your api. you are calling a method to add your option to the database. Are you also calling your api to read your options to the control?
- by
Tony
Top achievements
Rank 1
Iron
Iron
Iron
on 08 Jun 2021, 09:04 PM | edited
Asked by
Wassim
Top achievements
Rank 1
Iron
Answers by
Ivan Danchev
Telerik team
Wassim
Top achievements
Rank 1
Iron
Share this question
or