为什么属性DEPARTMENTID
在创建时没有插入数据库,我正在使用Dropdownlist
看到下面的代码,这是我的所有代码,我需要你的想法来纠正我的代码。
控制器
// GET: /Budget/Create
public ActionResult Create()
{
var name = User.Identity.GetUserName();
var userroles = _roleDataContext.USERROLEs.Where(u => u.USERNAME.ToLower().Trim() == name.ToLower().Trim() && u.ROLE.Trim() == "6");
var rolegroup = from u in userroles.ToList()
join rg in _roleDataContext.ROLEGROUPs.ToList()
on u.ROLEID equals rg.ROLEID
select rg;
var usergroup = (from rg in rolegroup.ToList()
join ug in _roleDataContext.USERGROUPs.ToList()
on rg.GROUPID equals ug.GROUPID
select ug).OrderBy(i => i.DEPTCODE);
var listSelectitem = usergroup.Select(@group => new SelectListItem
{
Selected = true,
Text = @group.DEPTCODE.Length > 20 ? @group.DEPTCODE.Substring(0, 20) : @group.DEPTCODE,
Value = @group.DEPTCODE
}).ToList();
var firstOrDefault = usergroup.FirstOrDefault();
if (firstOrDefault != null)
{
ViewBag.DeptList = new SelectList(listSelectitem, "Value", "Text", firstOrDefault.DEPTCODE);
}
return View();
}
// POST: /Budget/Create
[HttpPost]
public ActionResult Create(BudgetViewModel model , int month = 1, int year = 2017)
{
// TODO: Add insert logic here
model.DATETIME = DateTime.Now;
BudgetDb.insert(model);
return RedirectToAction("Index");
}
查看
@model WarehouseRtoRSystem.Models.BudgetViewModel
@{
ViewBag.Title = "Create";
}
<style>
.col-md-10 {
clear: both;
padding-left: 0px !important;
}
.col-md-2 {
text-align: left !important;
}
</style>
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
<div class="form-horizontal">
<h2>Budget</h2>
<hr />
@Html.ValidationSummary(true)
<label>Month </label>
<select id="month" name="month">
@{ string[] Months = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" }; }
@for (var i = 0; i < 12; i++)
{
var m = i + 1;
if (Convert.ToInt32(ViewBag.month) == m)
{
<option value=@m selected>@Months[i]</option>
}
else
{
<option value=@m>@Months[i]</option>
}
}
</select>
<label>YEAR</label>
<select id="year" name="year">
@for (var c = 0; c < 1000; c++)
{
var yr = c + 2017;
if (Convert.ToInt32(ViewBag.year) == yr)
{
<option value=@yr selected>
@yr
</option>
}
else
{
<option value=@yr> @yr</option>
}
}
</select>
<br />
<br />
<div class="form-group">
<label> LIST OF YOUR DEPARTMENT</label>
<span class="">@Html.DropDownList("DEPARTMENTID", (SelectList)ViewBag.DeptList, new { @class = "form-control" })</span>
</div>
<div class="form-group">
@Html.LabelFor(model => model.BUDGET, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.TextBox("ShowBudget", null, new { @class = "form-control" })
@Html.HiddenFor(model => model.BUDGET, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.BUDGET)
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="Create" class="btn btn-default" />
</div>
</div>
<br />
<br />
<br />
</div>
}
<div>
@Html.ActionLink("Back to List", "Index", null, new { @class ="btn btn-primary"})
</div>
<script>
$(document).ready(function () {
$("#ShowBudget").change(function () {
var value = parseFloat($(this).val());
$("#BUDGET").val(value); //assign the current value to BUDGET field
if (!isNaN(value)) {
var result = value.toLocaleString(
"en-US", // use a string like 'en-US' to override browser locale
{ minimumFractionDigits: 2 }
);
$(this).val(result);
}
})
})
</script>
@section Scripts {
@Scripts.Render("~/bundles/jqueryval")
}
模型
namespace WarehouseRtoRSystem.Models
{
public class BudgetModel
{
public int MONTH { get; set; }
public int YEAR { get; set; }
public string DEPARTMENTID { get; set; }
public DateTime DATETIME { get; set; }
//[DisplayFormat(DataFormatString = "{0:N}", ApplyFormatInEditMode = true)]
public double BUDGET { get; set; }
public string GROUPID { get; set; }
}
public class BudgetViewModel : BudgetModel
{
public string DEPARTMENTNAME { get; set; }
public double EXPENCES { get; set; }
public double BALANCE { get; set; }
}
public class BudgetContext
{
private readonly OracleCommand cmd = new OracleCommand();
private OracleConnection Conn = new OracleConnection();
private readonly OracleConnModel ORCONN = new OracleConnModel();
public List<BudgetViewModel> List()
{
var Departments = new List<BudgetViewModel>();
///SQL QUERY
Conn = ORCONN.con;
if (Conn.State != ConnectionState.Open)
{
Conn.Open();
}
try
{
cmd.Connection = Conn;
cmd.CommandText = "SELECT * From PH.SYSTEMBUDGET";
cmd.CommandType = CommandType.Text;
var dr = cmd.ExecuteReader();
while (dr.Read())
{
var Dept = new BudgetViewModel();
Dept.MONTH = dr.GetInt32(0);
Dept.YEAR = dr.GetInt32(1);
Dept.DEPARTMENTID = dr.GetString(2);
Dept.DATETIME = dr.GetDateTime(3);
Dept.BUDGET = dr.GetDouble(4);
Dept.GROUPID = dr.IsDBNull(5) ? "" : dr.GetString(5);
Departments.Add(Dept);
}
}
finally
{
Conn.Close();
}
return Departments;
}
public string insert(BudgetModel model)
{
Conn = ORCONN.con;
if (Conn.State != ConnectionState.Open)
{
Conn.Open();
}
try
{
cmd.Connection = Conn;
//var date = new DateTime();
// date = DateTime.Now;
var query = "INSERT into PH.SYSTEMBUDGET(";
query += "MONTH,";
query += "YEAR,";
query += "DEPARTMENTID,";
query += "DATETIME,";
query += "BUDGET,";
query += "GROUPID";
query += ")";
query += "VALUES(";
query += "'" + model.MONTH + "',";
query += "'" + model.YEAR + "',";
query += "'" + model.DEPARTMENTID + "',";
query += "TO_DATE('" + DateTime.Now + "','MM/DD/YYYY HH:MI:SS AM'),";
query += "'"+ model.BUDGET + "'," ;
query += "'" + model.GROUPID + "'";
query += ")";
cmd.CommandText = query;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
catch(Exception e)
{
Console.WriteLine("{0} Exception caught.", e);
}
finally
{
Conn.Close();
}
return "Seccessfully inserted";
}
}
}
答案 0 :(得分:0)
错误位于控制器中的以下代码中,您将Value
的{{1}}设置为DEPTCODE描述而不是DEPTCODE记录的ID
这是你的代码:
SelectListItem
问题在于:
var listSelectitem = usergroup.Select(@group => new SelectListItem
{
Selected = true,
Text = @group.DEPTCODE.Length > 20 ? @group.DEPTCODE.Substring(0, 20) : @group.DEPTCODE,
Value = @group.DEPTCODE
}).ToList();
现在很抱歉没有在控制器中完全重新创建代码,但是DEPTCODE模型不可用,所以我稍作即兴。
这是我的创建控制器:
Value = @group.DEPTCODE
我已使用记录[HttpGet]
public ActionResult Create()
{
List<DeptCode> _depts = new List<DeptCode>();
_depts.Add(new DeptCode { Id = 0, Description = "IT"});
_depts.Add(new DeptCode { Id = 1, Description = "Customer Services" });
_depts.Add(new DeptCode { Id = 2, Description = "Warehouse" });
var _listSelectItem = _depts.Select(@group => new SelectListItem
{
Selected = true,
Text = @group.Description,
Value = @group.Id.ToString()
}).ToList();
var firstOrDefault = _listSelectItem.FirstOrDefault();
if(firstOrDefault != null)
{
ViewBag.DeptList = new SelectList(_listSelectItem, "Value", "Text", firstOrDefault.Text);
}
return View();
}
的{{1}}创建了我的SelectListItem
,因为在您的代码中,您使用Value
绑定Id
其中ViewBag.DeptList
(Source)属性&#34;值&#34;。:
SelectList
所以在我的例子中,我选择了一个仓库部门(我再次为了我的模型而设置了这个值),然后按创建。:
如您所见,现在这已经绑定到dataValueField
D:
如果你想看看它是如何工作的,我在这里添加了我的代码: