2017-07-03 199 views
-3

爲什麼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 [email protected] selected>@Months[i]</option> 
 
} 
 
else 
 
{ 
 
<option [email protected]>@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 [email protected] selected> 
 
@yr 
 
</option> 
 
} 
 
else 
 
{ 
 
<option [email protected]> @yr</option> 
 
} 
 
} 
 
</select> 
 
<br /> 
 
<br /> 
 
<div class="form-group"> 
 
<label>&nbsp; &nbsp;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

您是否收到任何錯誤?它是否在你的httppost創建中一路暢通? – ljpv14

+0

沒有錯誤先生會顯示 –

+0

你可以在你的視圖模型上發佈代碼嗎?也是整個表單的html/razor代碼,而不僅僅是下拉列表。 – ljpv14

回答

0

錯誤駐留在你的控制器下面的代碼,因此您在設置SelectListItemValue是DEPTCODE描述,而不是DEPTCODE記錄的ID

這裏是你的代碼:

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(); 

問題就在這裏:

Value = @group.DEPTCODE 

現在很抱歉無法精確地在控制器中重新創建代碼,但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(); 
} 

我創建了我,因爲在你的代碼SelectListItem與記錄的Id,的Value,你用SelectList由此dataValueFieldSource)結合ViewBag.DeptList物業是「價值」。

ViewBag.DeptList = new SelectList(_listSelectItem, "Value", "Text", firstOrDefault.Text); 

所以在我的例子中,我選擇了一個倉庫部門(再次我做了這個值,爲我的模型的緣故),並按下創建。

My View

正如你所看到的,這是現在勢必model.DEPARTMENTI d:

enter image description here

我在這裏添加我的代碼,如果你想看看它是如何工作的:

https://github.com/garfbradaz/StackOverFlowAnswers/tree/master/ASP.NET%20MVC/DropDownListNotWorking/SOAnswer-44879268