我首先要说的是我对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>
}
我想我包括了一切。如果你看到遗漏的东西,请告诉我,但这对我有用。
答案 0 :(得分:0)
如果我理解你的问题:
更改
ddlCounties.append($('<option> </option>').val(option.id).html(option.name));
到
ddlCounties.append($('<option> </option>').val(option.name).html(option.name));
你的模型也应该有名字。
答案 1 :(得分:0)
我知道这已经过时了,但我找到了一个解决方案并想在此发布。已经有一段时间了,因为我修复了我的问题,所以我不记得我找到了解决方案的位置,但现在是:
控制器
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>
}
我想我包括了一切。如果你看到遗漏的东西,请告诉我,但这对我有用。