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
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.
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 ?
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();
}
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 ?
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>
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);
})
)
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; }
}
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();
I work with this in my entire solution.
I can't seem to send multiselected values and save in my sql table.
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?