Trying to load a Drop down and I am getting this error in my view:
Value cannot be null or empty.
Parameter name: name
This is the Controller
static List<AccountList> _acc = new List<AccountList>();
public ActionResult Index()
{
_acc = GetAccounts();
return View(_acc);
}
private List<AccountList> GetAccounts()
{
List<AccountList> temp = new List<AccountList>();
string sSource = "Test";
string sClinicId = "4";
string sStatus = null;
//This is simply retrieving the class from the web service where the list data is stored
ReconUIDataLayer.ClinicAccts retClinicAccts = new ReconUIDataLayer.ClinicAccts();
retClinicAccts = ReconUIDataLayer.UIDataLayer.LoadAccountInfo(sSource, sClinicId, ref sStatus);
temp = (from rows in retClinicAccts.ClinicAccts
select new AccountList
{
Text = rows.AcctName.ToString(),
Value = rows.AcctName.ToString(),
}).ToList();
return temp;
}
This is the View:
#model IEnumerable<C1MvcWebApplication3.Models.AccountList>
#using C1MvcWebApplication3.Models
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<table>
<tr><td>#Html.DropDownList("", new SelectList(Model.Select(x => new { Value = x, Text = x}),"AcctName","AcctName"))</td></tr>
</table>
</div>
</body>
</html>
The error is occurring on the helper to create the drop down.
I actually did two things to fix this:
1) just moved the List into my Controller
public ActionResult Index()
{
List<AccountList> _acc = new List<AccountList>();
_acc = GetAccounts();
return View(_acc);
}
I somehow think I didn't need to move the List declaration into the ActionResult and it may bite me later by not making it static.
2) Changed the call in my View
#Html.DropDownList("AccountList",new SelectList(Model, "Value", "Text"),"-Select")
Controller Code
readonly DBDashboardEntities DB = new DBDashboardEntities();// DB Entity Object
public ActionResult Index()
{
//using viewdata
ViewData["SelectDropDown_List"] =new SelectList(DB.tblStudents.ToList(), "studID", "studName");
//using viewbag
ViewBag.SelectDropDownList = new SelectList(DB.tblStudents.ToList(), "studID", "studName");
return View();
}
View Page code: index.cshtml
<tr>
<td>
#Html.DropDownListFor(c => c.studName, new SelectList(
new List<Object>{
new { value = 0 , text = "Rose" },
new { value = 1 , text = "John" },
new { value = 2 , text = "Smith"}
},
"value",
"text", 2))
</td>
<td>
#Html.DropDownListFor(c => c.studID, ViewData["SelectDropDown_List"] as SelectList) #*ViewData requires type casting*#
</td>
<td>
#Html.DropDownList("SelectDropDownList") #*String must be same as ViewBag.SelectDropDownList*#
</td>
</tr>
Related
I'm reading data from new tables using a SQL returning a datatable and able to show it in a view using the datatable as a model but the post/submit does not return anything, except in the HttpContext.Request.Form.
The new table column names cannot be determined except using SQL, so cannot use a model
// GET: /Home/
public async Task<IActionResult> Edit()
{
var conn = _context.Database.GetDbConnection();
await conn.OpenAsync();
var command = conn.CreateCommand();
command.CommandText = "SELECT * FROM NewTable";
var reader = await command.ExecuteReaderAsync();
DataTable dt = new DataTable();
dt.Load(reader);
dt.PrimaryKey = new DataColumn[]
{
dt.Columns["id"],
dt.Columns["idd"],
dt.Columns["idf"]
};
return View(dt);
}
#using System.Data
#model DataTable
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Edit</title>
</head>
<body>
<form asp-controller="Dynam" asp-action="Edit" method="post">
<table>
<tr>
#foreach (System.Data.DataColumn column in Model.Columns)
{
<td>#column.ColumnName</td>
}
</tr>
#for (var i = 0; i < Model.Rows.Count; i++)
{
var row = Model.Rows[i];
<tr>
#foreach (System.Data.DataColumn column in Model.Columns)
{
if (column.ColumnName == "id")
{
#Html.Hidden(column.ColumnName, row[column.ColumnName] )
}
else
{
<td>#Html.TextBox(column.ColumnName + "[" + i.ToString() + "]", row[column.ColumnName])</td>
}
}
</tr>
}
</table>
<div class="form-group">
<button type="submit" value="save" class="btn btn-default">Submit</button>
</div>
</form>
<div></div>
</body>
</html>
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(DataTable dt)
{
var commandText = "UPDATE MyTable SET #NewColumn = ('123xyz') " +
"WHERE Id = #Id AND Idd = #Idd AND Idf = #IDF";
var first = true;
foreach (string key in HttpContext.Request.Form.Keys)
{
// build sql for update
For example I create a model like this
using System.Collections.Generic;
namespace WebMvcApp.Models
{
public class DynamicTable
{
public string name { get; set; }
public List<Dictionary<string, string>> properties { get; set; }
}
}
I set all the rows as a List and all of the Column as a Dictionary. Then I create a test data like this:
public IActionResult Index()
{
var map1 = new Dictionary<string, string> {
{ "key1", "valueA1" },
{ "key2", "valueA2" },
{ "key3", "valueA3" }
};
var map2 = new Dictionary<string, string> {
{ "key1", "valueB1" },
{ "key2", "valueB2" },
{ "key3", "valueB3" }
};
var table = new List<Dictionary<string, string>>
{
map1,
map2
};
var entity = new DynamicTable
{
name = "table1",
properties = table
};
return View(entity);
}
Then I can deal with it in my view like this:
#model DynamicTable
<table>
<tr>
#foreach (var entry in Model.properties[0])
{
<td>#entry.Key</td>
}
</tr>
#{
foreach (var item in Model.properties)
{
<tr>
#foreach(var keypair in item)
{
<td>#keypair.Value</td>
}
</tr>
}
}
</table>
I have dropdownlst which i have filled from database. Now i need to get the selected value in Controller do some manipulation. But null data will get. Code which i have tried.
##View##
#using (Html.BeginForm()) {
#Html.DropDownList("SupplierId", ViewBag.PurSupName as SelectList, new {#class = "form-control",style = "width: 200px;",id="supId"})
}
## Controller ##
public ActionResult ItemPurchased()
{
POS_DBEntities2 db = new POS_DBEntities2();
var query = from i in db.TBL_Account
where i.Type == "supplier"
select i;
ViewBag.PurSupName = new SelectList(query, "AccountId", "AccountName");
return PartialView("ItemPurchased", new List<PurchasedItem>());
}
##Controller##
public ActionResult GetPurchasedItem()
{
var optionsValue = this.Request.Form.Get("SupplierId");
return View();
}
You can try with below changes.
#using (Html.BeginForm("GetPurchasedItem","YourController")) {
#Html.DropDownList("SupplierId", ViewBag.PurSupName as SelectList, new {#class = "form-control",style = "width: 200px;",id="supId"})
<input type="submit" value="OK" />
}
Controller will be
[HttpPost]
public ActionResult GetPurchasedItem(string SupplierId)
{
var optionsValue = SupplierId;
//..............
return View();
}
It should work normally..
I need you help with my mvc4 project. I have 2 drop down menus. When i select firs one, the second is automatically populated with help of Jquery and Ajax. When i select the other one, which is now populated with some data, i need to invoke a method which calls a PL/SQL procedure, and i need to pass a value to that method, which is selected in a second drop down menu.
That method returs some data which I need to pass to my partial view and in that partial view i need to generate a tree view from passed data.
So far i was able to generate TreeView (using jsTree) in my partial view when i hardcoded a value and invoked my method from controler, but i need to do that when i select a value from my second drop down list.
This is my code:
My Controller
public class IndexController : Controller
{
public ActionResult Index()
{
EpfeSelectScreen model = new EpfeSelectScreen();
#region Country
var b = (from a in dbEntitiesErste.CONFIG_COUNTRIES
orderby a.COUNTRY_ID
select new Countries
{
Text = a.COUNTRY_NAME,
Value = a.COUNTRY_ID
});
model.Country = b.OrderBy(x => x.Text).ToList();
#endregion
#region Oracle Stored Procedures
List<TreeNode> list = new List<TreeNode>();
list = ClassData.GetAllClasses(1); //hardcoded value 1 Here goes the value from second drop down list
var TopHierarchy = list.Where(x => x.ParentId == -1).FirstOrDefault();
SetChildren(TopHierarchy, list);
#endregion
var pmViewModel = new MainViewModel
{
FullModelObject = model,
PartialModelObject = TopHierarchy
};
return View(pmViewModel);
}
#region generate Tree
private void SetChildren(TreeNode model, List<TreeNode> list)
{
var childs = list.Where(x => x.ParentId == model.ChildId).ToList();
if (childs.Count > 0)
{
foreach (var child in childs)
{
SetChildren(child, list);
model.Children.Add(child);
}
}
}
#endregion
#region jquery methods
[OutputCache(Duration = 0)]
[HttpGet]
public JsonResult Application(string[] Country)
{
var apl = new List<Applications>();
if (Country[0] == "")
{
//*aplications
var result = (from a in dbEntitiesErste.CONFIG_APPLICATIONS
select new Applications
{
Text = a.APPLICATION_NAME,
Value = a.APPLICATION_ID
});//*.OrderBy(x => x.Text).ToList()
apl.Add(new Applications { Value = 0, Text = "--Please choose application--" });
apl.AddRange(result.OrderBy(x => x.Text).ToList());
}
else
{
var result = (from a in dbEntitiesErste.CONFIG_APPLICATIONS
where Country.Contains(a.COUNTRY_ID)
select new Applications
{
Text = a.APPLICATION_NAME,
Value = a.APPLICATION_ID
}); //*.OrderBy(x => x.Text).ToList();
apl.Add(new Applications { Value = 0, Text = "--Please choose application--" });
apl.AddRange(result.OrderBy(x => x.Text).ToList());
}
var retVal = new { Application = aplikacije };
return Json(retVal, JsonRequestBehavior.AllowGet);
}
//[OutputCache(Duration = 0)]
//[HttpGet]
//public JsonResult Tree(int idApp)
//{
// var ret = (from a in dbEntitiesErste.CONFIG_APPLICATIONS
// select new Applications
// {
// Text = a.APPLICATION_NAME,
// Value = a.APPLICATION_ID
// }).OrderBy(x => x.Text).ToList();
// return Json(ret, JsonRequestBehavior.AllowGet);
//}
#endregion
}
this is my main View (Index.cshtml)
#model EPFE.Models.ViewModels.MainViewModel
<!DOCTYPE html>
#{
ViewBag.Title = "EB";
}
<head>
<title>EBB</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<script src="#Url.Content("~/Scripts/jquery-ui-1.10.3.js")" type="text/javascript"></script>
<script src="~/Scripts/Selections.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<script src="#Url.Content("~/Scripts/jstree.js")" type="text/javascript"></script>
<link href="#Url.Content("~/Content/Selection.css")" rel="stylesheet" type="text/css" />
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="#Url.Content("~/Content/themes/style.css")" rel="stylesheet" />
<script type="text/javascript">
var pathAplications = '#Url.Action("Application", "Index")';
var pathTreeView = '#Url.Action("Tree", "Index")';
</script>
</head>
<body>
<table>
<tr>
<td>
#Html.DropDownList("Country", new SelectList(Model.FullModelObject.Country, "Value", "Text"), "--Please select Country--")
</td>
</tr>
<tr>
<td>
#Html.DropDownList("Application", new SelectList(Model.FullModelObject.Application, "Value", "Text"), "--Please choose application--")
</td>
</tr>
</table>
<fieldset class="Tree">
<div id="divtree">
<ul id="tree">
<li>
#Model.PartialModelObject.ObjectIdentifier
#Html.Partial("_TreeView", Model.PartialModelObject)
</li>
</ul>
</div>
</fieldset>
</body>
This is my partial view (_TreeView.cshtml)
#model EPFE.TreeViewModel.TreeNode
#foreach (var item in Model.Children)
{
<ul>
#if (item != null)
{
<li>
#item.ObjectIdentifier
#if (item.Children.Count > 0)
{
#Html.Partial("_TreeView", item)
}
</li>
}
</ul>
}
and these are my models
public class EpfeSelectScreen
{
public string Search { get; set; }
public string selectedApplication { get; set; }
public string selectedCountry { get; set; }
public string selectedMetaData { get; set; }
public string selectedTreeView { get; set; }
public List<Countries> Country { get; set; }
public List<Applications> Application { get; set; }
public List<SelectListItem> MetaData { get; set; }
public List<SelectListItem> References { get; set; }
public List<SelectListItem> ReferencedBy { get; set; }
public List<SelectListItem> TreeView { get; set; }
public EpfeSelectScreen()
{
Country = new List<Countries>();
Application = new List<Applications>();
References = new List<SelectListItem>();
ReferencedBy = new List<SelectListItem>();
TreeView = new List<SelectListItem>();
MetaData = new List<SelectListItem>();
}
}
Second one
public class MainViewModel
{
public EpfeSelectScreen FullModelObject { get; set; }
public TreeNode PartialModelObject { get; set; }
public MainViewModel()
{
FullModelObject = new EpfeSelectScreen();
PartialModelObject = new TreeNode();
}
}
and the last one
public class TreeNode
{
public int ParentId { get; set; }
public int ChildId { get; set; }
public int ObjectRelId { get; set; }
public string ObjectIdentifier { get; set; }
public string ObjectTypeId { get; set; }
public IList<TreeNode> Children { get; set; }
public TreeNode()
{
Children = new List<TreeNode>();
}
}
and these are my scripst
$(document).ready(function () {
$("#Country").on('change', CountryChange);
//$("#selectedApplication").on('change', ApplicationChange);
//*
$("#Application").on('change', ApplicationChange);
});
function CountryChange() {
var CountryIds = [];
$("#Country option:selected").each(function (i, selected) {
CountryIds[i] = $(selected).val();
});
$.ajax({
url: pathAplications,
type: 'GET',
data: { Country: CountryIds },
success: function (data) {
var apl = $("#Application");
apl.empty();
for (var j = 0; j < data.Application.length; j++) {
var item = data.Application[j];
var option = "<option value='" + item.Value + "'>" + item.Text + "</option>";
apl.append(option);
}
},
error: function (x, y) {
$("#displayError").html(x.val());
},
traditional: true
});
}
function ApplicationChange() {
var applicationId = [];
$("#Application option:selected").each(function (i, selected) {
applicationId[i] = $(selected).val();
});
$.ajax({
url: pathTreeView,
type: 'GET',
data: { Application: applicationId },
success: function (data) {
var tree = $("#selectedApplication");
trees.empty();
for (var j = 0; j < data.Application.length; j++) {
var item = data.Application[j];
var option = "<option value='" + item.Value + "'>" + item.Text + "</option>";
trees.append(option);
}
},
error: function (x, y) {
$("#displayError").html(x.val());
},
traditional: true
});
}
The function ApplicationChange catches the right value but i don't know how to use it to invoke my method for pl/sql procedure and return that data to partial view.
give your url like this
'#Url.Action("actionname","controllerNmae")',
also make sure if you are making a get or post request then the target action should have that attribute as well.
also you data type will be json for this.
or even better use like this
$.getJSON('#Url.Action("Controller Name here")',
function ()
{
});
i stored few images in database in binary format, now i want to display those images in my view,how can we convert those images from binary format to image format again?
this is my action menthod in my controller
public ActionResult DislpayAllImage()
{
DataSet dsa = new DataSet();
dsa = objImage.getAllImages();
DataTable dt = new DataTable();
dt = dsa.Tables[0];
if (dt != null)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Byte[] image = (Byte[])dt.Rows[i]["UsImage"];
return File(image, "image/jpg");
}
}
return View();
}
this is my code in model
public DataSet getUserImage(int Id)
{
DataSet ds = new DataSet();
try
{
DbCommand db = dbcon.GetStoredProcCommand("GetImage");
dbcon.AddInParameter(db, "#Id", DbType.Int16, Id);
db.CommandType = CommandType.StoredProcedure;
return ds = dbconstr.ExecuteDataSet(dbCmd);
}
catch(Exception ex)
{
return ds = null;
}
}
view
#foreach( var image in ViewData.Images )
{
<img src="#Url.Action("DislpayImage", "Home",new { id = image.ImageID })" />
}
how can i display my image in razor view,also is the above code fine?
You need to call your Controller's Action(DislpayImage()) from the View like this:
<img src="<%= Url.Action("DislpayImage", "Controller") %>" alt="myimage" />
or
<img src="#Url.Action("DislpayImage", "Controller")" alt="myimage" />
Hope it helps you.
Edit
Just pass the id of the image you want to display to Controller action
public ActionResult DislpayImage(int id)
{
DataSet dsa = new DataSet();
dsa = objImage.getUserImage(id);
var imagedata = dsa.Tables[0].Columns["MyImage"];
return File(imagedata, "image/jpg");
}
Now pass the id of image which you want to display in your view, like this:
<img src="#Url.Action("DislpayImage", "Controller", new { id="2" })" alt="myimage" />
Now you will get the image with id as 2.
<% foreach( var image in ViewData.Images ) { %>
<%= Html.Image( Url.Action( "Show", "Image", new { id = image.ImageID } ) ) %>
<% } %>
public class ImageController : Controller
{
public void Show(string id)
{
Image image = GetImage(id);
Response.Buffer = True;
Response.Clear();
Response.ContentType = "image/gif";
Response.BinaryWrite( image.Data );
Response.End();
}
}
This response is just a copy of an answer from another forum.
This is not my own. I'm pasting it here to help you and someone else in this forum
with the same issue.
Here is the main link: http://forums.asp.net/post/2264885.aspx
I use a callback panel inside a form and when the Combobox Value changes the values of the fields inside the CallbackPanel should be updated accordingly.
My issue is that the model values are always null inside the controller and i do not know why! (model.Documents = null and model.SelectedDocument = null)
It would be great if someone could tell me where my issue is and how to solve it.
Here is my code(edited):
View
#using (Html.BeginForm("Finalize", "DocumentsWaitingApproval", FormMethod.Post, Model))
{
<table>
<tr>
<td>
#Html.DevExpress().ComboBox(settings =>
{
settings.SelectedIndex = 0;
settings.Properties.TextField = "Title";
settings.ClientEnabled = true;
settings.Properties.ClientInstanceName = "CmbBoxFiles";
settings.Properties.EnableClientSideAPI = true;
settings.Properties.ValueType = typeof(int);
settings.Properties.ValueField = "DocumentID";
settings.Name = "CmbBoxFiles";
settings.Properties.ClientSideEvents.SelectedIndexChanged = "function(s,e) { cmbBoxFiles_SelectedIndexChanged(s,e); }";
}).BindList(Model.Documents).GetHtml()
</td>
</tr>
</table>
#Html.DevExpress().CallbackPanel(
settings =>
{
settings.Name = "cbpDocWaiting";
settings.CallbackRouteValues = new { Controller = "DocumentsWaitingApproval", Action = "Refresh" };
Controller Methods
[Authorize]
public ActionResult Refresh(DocumentsWaitingApprovalModel model) // model.SelectedDocument is always null
{
}
[Authorize]
public ActionResult Finalize([Bind]DocumentsWaitingApprovalModel model) //model.SelectedDocument is always null
{
return RedirectToAction("Index");
}
}