【发布时间】:2014-10-16 08:47:13
【问题描述】:
我首先要说我对 asp.net MVC 很陌生,但是有一个项目需要完成。话虽如此,任何帮助都非常感谢。
我创建了两个级联下拉列表,并使用 MVC、LINQ to SQL 和 Ajax 进行填充,我需要将这些选择带入我的控制器。我试图简单地创建和发送一封电子邮件,其中包含我的表单数据,并且已经卡住了一段时间。 Javascript 从数据库返回 ID 号,但我需要与 Id 相关联的“StateName 和“CountyName”,而不仅仅是 Id。作为参考,这是我用来创建我现在拥有的东西的方法,但没有说明如何提交选择。
http://www.codeproject.com/Articles/730953/Cascading-Dropdown-List-With-MVC-LINQ-to-SQL-and-A
这是我的控制器
public class AddressController : Controller
{
private IAddressRepository _repository;
public AddressController() : this(new AddressRepository())
{
}
public AddressController(IAddressRepository repository)
{
_repository = repository;
}
public ActionResult Index()
{
AddressModel model = new AddressModel();
model.AvailableUSStates.Add(new SelectListItem { Text = "-Please select-", Value = "Selects items" });
var usstates = _repository.GetAllUSStates();
foreach (var usstate in usstates)
{
model.AvailableUSStates.Add(new SelectListItem()
{
Text = usstate.USStateName,
Value = usstate.USStateID.ToString()
});
}
return View(model);
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetCountiesByUSStateID(string USStateID)
{
if (string.IsNullOrEmpty(USStateID))
{
throw new ArgumentNullException("USStateID");
}
int id = 0;
bool isValid = Int32.TryParse(USStateID, out id);
var counties = _repository.GetAllCountiesByUSStateID(id);
var result = (from s in counties
select new
{
id = s.CountyID,
name = s.CountyName
}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
[HttpPost]
public ContentResult SimplePost(string submittedState)
{
string result = string.Format(submittedState);
return new ContentResult { Content = result };
}
[AcceptVerbs(HttpVerbs.Post)]
public async Task<ActionResult> Index([Bind(Include = "USStateName, CountyName")] AddressModel addressModel)
{
if (ModelState.IsValid)
{
MailMessage message = new MailMessage();
message.From = new MailAddress("address@gmail.com");
message.To.Add(new MailAddress("address@hotmail.com"));
message.Subject = "";
message.Body = "";
SmtpClient client = new SmtpClient();
client.Send(message);
return View("Index");
}
else
{
return View();
}
}
}
型号
namespace msifla.Models
{
public class AddressModel
{
public AddressModel()
{
AvailableUSStates = new List<SelectListItem>();
AvailableCounties = new List<SelectListItem>();
}
[Display(Name = "USState")]
public int USStateID { get; set; }
public List<SelectListItem> AvailableUSStates { get; set; }
[Display(Name = "County")]
public int CountyID { get; set; }
public List<SelectListItem> AvailableCounties { get; set; }
}
}
查看
@model msifla.Models.AddressModel
@{
ViewBag.Title = "Index";
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#USStateID").change(function () {
var selectedItem = $(this).val();
var ddlCounties = $("#CountyID");
var countiesProgress = $("#counties-loading-progress");
$('.selItem').remove();
var selectedItem2 = $('<p class="selItem">' + selectedItem + '</p>');
$('.usState').append(selectedItem2);
//$('.usState').append($('<p>This works here</p>'));
countiesProgress.show();
$.ajax({
cache: false,
type: "GET",
url: "@(Url.RouteUrl("GetCountiesByUSStateID"))",
data: { "USStateID": selectedItem },
success: function (data) {
ddlCounties.html('');
$.each(data, function (id, option) {
ddlCounties.append($('<option> </option>').val(option.id).html(option.name));
});
alert(option.name);
countiesProgress.hide();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve states.');
countiesProgress.hide();
}
});
});
});
</script>
@using (Html.BeginForm())
{
<div>
@Html.LabelFor(model => model.USStateID)
@Html.DropDownListFor(model => model.USStateID, Model.AvailableUSStates)
</div>
<br />
<div>
@Html.LabelFor(model => model.CountyID)
@Html.DropDownListFor(model => model.CountyID, Model.AvailableCounties)
<span id="counties-loading-progress" style="display: none;">Please wait..</span>
</div>
<div class="usState"></div>
<input name="submit" type="submit" id="submit" value="Save"/>
<label id="stateLabel"></label>
}
如果您需要查看存储库,请告诉我。 提前感谢您的帮助。
编辑 我知道这很旧,但我找到了一个解决方案并想在这里发布。我已经有一段时间没有解决我的问题了,所以我不记得我在哪里找到了解决方案,但这里是:
控制器
public ActionResult Index()
{
AddressModel model = new AddressModel();
model.AvailableUSStates.Add(new SelectListItem { Text = "-Please select-", Value = "Selects items" });
model.AvailableLibraries.Add(new SelectListItem { Text = "-Please select-", Value = "Selects items" });
var usstates = _repository.GetAllUSStates();
foreach (var usstate in usstates)
{
model.AvailableUSStates.Add(new SelectListItem()
{
Text = usstate.USStateName,
Value = usstate.USStateID.ToString()
});
}
return View(model);
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult GetLibrariesByUSStateID(string USStateID)
{
if (string.IsNullOrEmpty(USStateID))
{
throw new ArgumentNullException("USStateID");
}
int id = 0;
bool isValid = Int32.TryParse(USStateID, out id);
var counties = _repository.GetAllLibrariesByUSStateID(id);
var result = (from s in counties
select new
{
id = s.LibraryID,
name = s.LibraryName
}).ToList();
return Json(result, JsonRequestBehavior.AllowGet);
}
[AcceptVerbs(HttpVerbs.Post)]
//[ValidateAntiForgeryToken]
public ActionResult Index(AddressModel model)
{
var errors = ModelState.Values.SelectMany(v => v.Errors);
if (ModelState.IsValid)
{
ConfirmModel model2 = new ConfirmModel();
model2.USStateName = SelectedUSState(model.USStateID.ToString());
model2.CountyName = SelectedCounty(model.LibraryID.ToString(), model.USStateID.ToString());
model2.CountyID = model.LibraryID;
model2.clientID = model.clientId.ToString();
return View("Confirmation", model2);
}
return View(model);
}
public ActionResult Confirmation(AddressModel model2)
{
ConfirmModel model = new ConfirmModel();
model.USStateName = SelectedUSState(model2.USStateID.ToString());
model.CountyName = SelectedCounty(model2.LibraryID.ToString(), model2.USStateID.ToString());
var USStateName = model.USStateName;
return View(model);
}
//[AcceptVerbs(HttpVerbs.Get)]
//public ActionResult Confirmation(ConfirmModel model)
//{
// string USStateName = model.USStateName;
// return View();
//}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult submitConfirmation(ConfirmModel model)
{
if (ModelState.IsValid)
{
string usStateName = model.USStateName;
string countyName = model.CountyName;
DateTime dateTime = DateTime.Now;
string ipAddress = Request.UserHostAddress;
string ipAddress2 = Request.ServerVariables["Remote_Addr"];
string userAgent = Request.UserAgent;
MailMessage message = new MailMessage();
message.From = new MailAddress("someone@domain.com");
message.To.Add(new MailAddress("someoneElse@domain.com"));
message.Subject = "Subject";
// You need to use Index because that is the name declared above
message.Body = "<!DOCTYPE html><head></head><body>" +
"<pre>State:\t\t" + usStateName + "</pre>" +
"<pre>County:\t\t" + countyName + "</pre>" +
"<pre>Remote Name:\t" + ipAddress + "</pre>" +
"<pre>Remote User:\t" + userAgent + "</pre>" +
"<pre>Date:\t" + dateTime.ToLongDateString() + "</pre>" +
"<pre>Time:\t" + dateTime.ToLongTimeString() + "</pre>" +
"\n"
"</body>";
message.IsBodyHtml = true;
SmtpClient client = new SmtpClient();
client.Send(message);
return RedirectToAction("Index");
}
return View(model);
}
[HttpPost]
public ActionResult resetConfirmation()
{
return RedirectToAction("Index");
}
public string SelectedUSState(string USStateID)
{
ViewBag.YouSelected = USStateID.ToString();
AddressModel model = new AddressModel();
int id = 0;
int usStateIDInt = int.Parse(USStateID);
bool isValid = Int32.TryParse(USStateID, out id);
var usstates = _repository.GetAllUSStates();
var state = from s in _repository.GetAllUSStates()
where s.USStateID.ToString() == USStateID
select s.USStateName;
var currUSState = state.SingleOrDefault();
//var currUSStatename = usstates.te
//model.USStateName = currUSState;
ViewBag.currUSState = currUSState;
return currUSState;
}
public string SelectedCounty(string CountyID, string USStateID)
{
AddressModel model = new AddressModel();
int id = 0;
int countyIDInt = int.Parse(CountyID);
bool isValid = Int32.TryParse(CountyID, out id);
int usStateIDInt = int.Parse(USStateID);
var counties = _repository.GetAllLibrariesByUSStateID(usStateIDInt);
var county = from s in counties
where s.LibraryID.ToString() == CountyID
select s.LibraryName;
var currCounty = county.SingleOrDefault();
ViewBag.currCounty = currCounty;
return currCounty;
}
型号
public class AddressModel
{
public AddressModel()
{
AvailableUSStates = new List<SelectListItem>();
AvailableLibraries = new List<SelectListItem>();
}
[Display(Name = "USState")]
[Required(ErrorMessage = ("Please choose a State"))]
public int USStateID { get; set; }
//public string USStateName { get; set; }
public List<SelectListItem> AvailableUSStates { get; set; }
[Display(Name = "Library")]
[Required(ErrorMessage = ("Please chose a Library for the selected State"))]
public int LibraryID { get; set; }
public List<SelectListItem> AvailableLibraries { get; set; }
}
public class ConfirmModel
{
[Display(Name = "State Name")]
public string USStateName { get; set; }
[Display(Name = "County Name")]
public string CountyName { get; set; }
}
查看
@model msifla2.Models.MSIProModel
@{
ViewBag.Title = "HCOrder";
}
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
@*<script src="~/Scripts/angular.min.js"></script>*@
@*<script src="~/Scripts/cascade.js"></script>*@
<script type="text/javascript">
$(function () {
$("#USStateDDL").change(function () {
var selectedItem = $(this).val();
var ddlLibraries = $("#LibraryID");
var librariesProgress = $("#libraries-loading-progress");
librariesProgress.show();
$.ajax({
cache: false,
type: "GET",
url: "@(Url.RouteUrl("GetLibrariesByUSStateID"))",
data: { "USStateID": selectedItem },
success: function (data) {
ddlLibraries.html('');
$.each(data, function (id, option) {
ddlLibraries.append($('<option>Select a Library</option>').val(option.id).html(option.name));
});
librariesProgress.hide();
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve libraries.');
librariesProgress.hide();
}
});
});
});
</script>
@*<script>
$(function () {
$('#USStateDDL').change(function () {
$.ajax({
url: this.href,
type: 'GET',
cache: false,
data: { selectedValue: $('#USStateDDL').val() },
success: function (result) {
alert('#USStateDDL').val();
}
})
var selected = $(this).val();
alert(selected + " 1 selected")
$('#USStateLabel').load(input)
});
});
</script>*@
<div class="jumbotron">
</div>
<div class="container article">
<div data-ng-app="myModule" class="col-md-9 article_main container-fluid">
<h2>Header</h2>
@using (Html.BeginForm("Address", "Home", FormMethod.Post))
{
<div class="edit-label">
@Html.LabelFor(model => model.USStateID, new { id = "USStateLabel", @class = "col-xs-3" })
</div>
<div class="edit-field, col-xs-9">
@Html.DropDownListFor(model => model.USStateID, Model.AvailableUSStates, new { @class = "form-control dropdowns", id = "USStateDDL" })
</div>
@Html.LabelFor(model => model.LibraryID, new { @class = "col-xs-3" })
<div class=" col-xs-9">
@Html.DropDownListFor(model => model.LibraryID, Model.AvailableLibraries, new { @class = "form-control" })
</div>
<div class="col-xs-9 col-xs-offset-3" style="padding-top:5px;">
<input type="submit" id="submit" value="Send" class="btn-success btn" />
</div>
}
</div>
</div>
</div>
</div>
确认查看
@model msifla2.Models.ConfirmModel
@{
ViewBag.Title = "Confirmation";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Confirmation</h2>
@using (Html.BeginForm("submitConfirmation", "Home", FormMethod.Post))
{
<div data-ng-app="myModule" class="col-md-9 article_main">
<div>
<h4>Please check your order and select <b>Confirm</b> to submit</h4>
</div>
<div class="row">
@Html.LabelFor(model => model.USStateName, new { @class = "col-xs-3" })
@Html.DisplayTextFor(model => model.USStateName)
@Html.HiddenFor(model => model.USStateName)
</div>
<div class="row">
@Html.LabelFor(model => model.CountyName, new { @class = "col-xs-3" })
@Html.DisplayTextFor(model => model.CountyName)
@Html.HiddenFor(model => model.CountyName)
</div>
<input type="submit" formaction="/home/submitConfirmation" value="Confirm" />
<input type="submit" formaction="/Home/resetConfirmation" value="Reset" />
</div>
}
我想我包含了所有内容。如果您发现缺少某些内容,请告诉我,但它对我有用。
【问题讨论】:
-
beurk,这么多的 JavaScript 代码。为什么不使用局部视图?
-
我会考虑使用部分视图,但是,我看不出这有助于实际使用我拥有的下拉框中的选定值。如果我错了,请纠正我,并提供一个例子。
-
如果你有 ID,你可以调用 $.ajax({url:'getPartialDDl?Id=...',success:function (data) { ddlCounties.load(data)然后你必须让你的方法getPartialDDl返回包含下拉列表的正确部分视图。但是是的,它无助于获取选定的值(我读到“Javascript从数据库返回ID号”所以我认为这部分是好的。)
标签: c# javascript asp.net-mvc submit html.dropdownlistfor