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>
Related
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>
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 have a radiobutton list in my create view.It is generated along with checkbox when selecting a dropdown.
#model IEnumerable<Admin.Models.viewmodel>
#foreach (var item in Model)
{
<label>
#Html.CheckBox("User", item.Selected, new { #id = "User" + item.Value, #value = item.Value })
#item.Text
</label>
<label>
#Html.RadioButton("rdnUser" + item.Value.TrimStart(), 1, item.IsSelected,new { #id = "rdnUser"})Primary
</label>
<label>
#Html.RadioButton("rdnUser" + item.Value.TrimStart(), 2,item.IsSelected, new { #id = "rdnUser"})Secondary
</label>
}
Iam saving the value of radiobutton to a field UserType in table UserMapping.
When I click on Edit link,I want to get the radiobutton selected according to database value..
Created a viewmodel to take values in checkbox and radiobutton.viewpartial viewmodel is:-
public class viewpartial : System.Web.Mvc.SelectListItem
{
public int Values { get; set; }
public bool IsSelected { get; set; }
}
The query is:-
var query = (from u in UserMapping
where u.UserID == id && u.Active == 1
join f in Financial on u.FinancialID equals f.FinancialID
into c
from d in c.DefaultIfEmpty()
select new viewpartialIFC
{
Text = d.FiName,
Value = SqlFunctions.StringConvert((double)d.FinancialID),
Selected = d.FinancialID == u.FinancialID ? true : false,
Values = u.UserType,
//IsSelected=???
}).Distinct().ToList();
what changes should i make in the query to get radiobutton selected..
This is a way that you can create a list of users and have the option to selected them (checkbox) and selected a particular role (radiobuttons):
ViewModel:
public class AdminViewModel
{
public int Id { get; set; }
public string Name { get; set; }
public bool isSelected { get; set; }
public int RadioValue { get; set; }
}
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var data = GenerateViews();
return View(data);
}
[HttpPost]
public ActionResult Index(IList<AdminViewModel> data)
{
var selectedViews = data.Where(d => d.isSelected == true);
foreach (var selected in selectedViews)
{
//selected.Id;
//selected.RadioValue;
}
System.Diagnostics.Debugger.Break();
return View(data);
}
private IList<AdminViewModel> GenerateViews()
{
var output = new List<AdminViewModel>();
var rand = new Random();
for (var count = 1; count <= 10; ++count)
{
var newView = new AdminViewModel();
newView.Id = count;
newView.Name = "Name " + count.ToString();
newView.isSelected = false;
newView.RadioValue = rand.Next(1, 3);
output.Add(newView);
}
return output;
}
}
View:
#model IList<WebMVC3.Controllers.AdminViewModel>
<h2>Index</h2>
#using (Html.BeginForm())
{
//foreach (var item in Model)
for(var index = 0; index < Model.Count; ++index)
{
<div>
#Html.HiddenFor(m => Model[index].Id)
<label>
#Html.CheckBoxFor(m => Model[index].isSelected, Model[index].isSelected)
#Model[index].Name
</label>
<label>
#Html.RadioButtonFor(m => Model[index].RadioValue, 1)
Primary
</label>
<label>
#Html.RadioButtonFor(m => Model[index].RadioValue, 2)
Secondary
</label>
</div>
}
<input type="submit" value="Save" />
}
I wanted to create a tree view using MVC3 control toolkit and bind the data from the database dynamically to the recursive list.
Step 1: Get the details from the db to the obj like List or ArrayList
Step 2: Assign the List to viewdata in controller Action Result like
viewdata["name"]=List;
Step 3: Assign the viewdata to another List in cshtml treeview
ArrayList col = (ArrayList)ViewData["name"];
#if (col != null)
{
Html.Telerik().TreeView()
.Name("HierarchyTreeView")
.Items(items =>
{
for (int i = 0; i < col.Count; i++)
{
items.Add()
.Text(col[i].ToString())
.Value().Selected(True)
.Items((subItem) =>
{
subItem.Add()
.Text(Child.ToString()) //Here place child value
.Value();
});
}
}).ClientEvents(events => events
.OnSelect("onSelect")
).Render();
}
Step 4: Using the List assign the value to the tree view nodes using nested for loop
Step 5: Write onselect client event and get the selected value from Javascript and assign it to the javascript method of Grid filter.
function onSelect(e) {
var HNKey = treeView().getItemValue(e.item);
var HNText = treeView().getItemText(e.item);
}
Hope this will give some idea to start your process then from this you can ask questions.
I finally found better solution for this question..
I used jquery to create the tree which was much helpful for me.
After seaching for long time, I found something like this:
public class TreeView
{
public static List<Model> GetAllCategories()
{
string query="select * from tableName";
string connString = "connectionString";
var itemList = new List<Model>();
using (var con = new SqlConnection(connString))
{
using (var cmd = new SqlCommand(qry, con))
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
//added my code here to get the data..
itemList.Add(
new Model(){
categoryId= reader.GetInt32(reader.GetOrdinal("categoryId"))
)};
}
}
}
}
return itemList;
}
}
In the controller I wrote my code as:
public ActionResult Index()
{
List<Model> itemList= new List<Model>();
itemList = TreeView.GetAllCategories();
var president = itemList.
Where(x => x.Model.PAId == 0).ToList(); //
foreach (var item in president)
{
SetChildren(item, itemList);
}
return View(president);
}
private void SetChildren(Model model, List<Model> itemList)
{
var childs = itemList.
Where(x => (x.Model.PAId == model.categoryId)).ToList();
if (childs.Count > 0)
{
foreach (var child in childs)
{
SetChildren(child, itemListList);
model.Categories.Add(child);
}
}
}
Index.cshtml :
<div id="divtree">
#foreach (var item in Model)
{
<ul id="tree" >
<li>
#Html.ActionLink(item.Model.categoryName, "Action")
#Html.Partial("Childrens", item)
</li>
</ul>
}
</div>
<script type="text/javascript">
$(function () {
$('#treeViewContent').load('#Url.Action("CreateCategory","Category")');
$('#divtree').jstree({
"plugins": ["themes", "html_data", "ui", "cookies"]
})
.bind('loaded.jstree', function () {
$(this).jstree('open_all');
});
});
</script>
Childrens.cshtml:
#foreach (var item in Model.Categories)
{
<ul>
#if (item != null)
{
<li>
#Html.ActionLink(item.Model.categoryName, "Action")
#if (item.Categories.Count > 0)
{
#Html.Partial("Childrens", item)
}
</li>
}
</ul>
}
and finally got tree like this: