我環顧四周,看看之前是否已經詢問過,並且找不到任何東西(所以如果確實在之前已經詢問過,那麼我很抱歉)使用jQuery刷新ASP.NET MVC 2中的列表框
下面是我想要做的,用戶可以從他們的個人資料的技能列表中選擇,如果他們想要的技能不在列表中,那麼他們可以將其添加到數據庫中,我已經使用WCF 。& jQuery的AJAX下面是該代碼:
$("#AddNewSkill").click(function() {
$("#AddNewSkill").attr("disabled", true);
$("#newSkill").attr("disabled", true);
var newSkill = $("#newSkill").val();
var data = { name: $("#newSkill").val(), description: "", type: "Skill" };
data = JSON.stringify(data)
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "../WeddingPhotographerService.svc/AddNew",
data: data,
dataType: "json",
success: function() {
successCall('#newSkill', '#AddNewSkill');
//$('#SkillListViewContainer').load('../Account/GetSkillControl');
},
error: function (msg) {
$("#AddSkillError").text(msg.d);
$("#AddSkill").attr("disabled", false);
$("#NewSkill").attr("disabled", false);
}
});
});
下面是在支持Ajax的WCF服務的方法:
[OperationContract]
public bool AddNew(string name, string description, string type)
{
switch (type)
{
case "":
goto default;
case "skill":
IRepository<Skill> skillRepo = ObjectFactory.GetInstance<IRepository<Skill>>();
var skill = new Skill { Name = name, Description = (string.IsNullOrEmpty(description)) ? string.Empty : description };
skillRepo.Save(skill);
return true;
case "equipment":
IRepository<Equipment> eqRep = ObjectFactory.GetInstance<IRepository<Equipment>>();
var eq = new Equipment { Name = name, Description = (string.IsNullOrEmpty(description)) ? string.Empty : description };
eqRep.Save(eq);
return true;
case "occasion":
IRepository<Occassion> occRepo = ObjectFactory.GetInstance<IRepository<Occassion>>();
var oc = new Occassion { Name = name, Description = (string.IsNullOrEmpty(description)) ? string.Empty : description };
occRepo.Save(oc);
return true;
default:
IRepository<Skill> repo = ObjectFactory.GetInstance<IRepository<Skill>>();
var s = new Skill { Name = name, Description = (string.IsNullOrEmpty(description)) ? string.Empty : description };
repo.Save(s);
return true;
}
}
這是一種醜陋的,但我會優化它,一旦我有這第二部分工作。這裏的ListBox中是如何被加載的觀點:
<%: Html.ListBox("Skills", Model.SkillList, new { @style = "width:157px; height:90px;background:#e2f0f1;", @size = "3", @class = "inputbox" })%>
它來自RegistrationModelView.cs,這裏的SkillList在我的模型視圖:
private MultiSelectList GetSkills(string[] selectedValues)
{
List<Skill> list = new List<Skill>();
IRepository<Skill> skills = ObjectFactory.GetInstance<IRepository<Skill>>();
foreach (Skill skill in skills.GetAll())
{
list.Add(new Skill()
{
Key = skill.Key,
Name = skill.Name,
Description = ""
});
}
return new MultiSelectList(list, "Key", "Name", selectedValues);
}
而且在的AccountController的動作。 CS加載視圖
[MoveFormsScript]
public ActionResult Index()
{
return View(new RegistrationModelView());
}
我很確定我發佈的所有代碼(除了新項目是如何與WCF服務一起添加的以及用於使用所述服務的jQuery是無關緊要的,但我認爲我會盡可能多地提供信息)。
就像我說的新值被添加到數據庫沒有問題,我的問題是更新ListBox以反映新值。任何人有任何想法,可以幫助嗎?