If a user is typing something into a textbox on a form, and what they are typing in starts to match a value that is already in the database, how do I get the textbox to give the option to auto-fill the rest of what the user wants to type in based on the value that is already in the database?
Consider I have this table(name of table: Person) in my database:
|ID| |FirstName| |LastName|
1 John Smith
2 Tom Jones
3 James Davis
and on the form where the user wants to create a new Person they start to type in jo into the FirstName textbox.. how do i get the textbox to give the option to autofill the hn and capitalize the first letter to spell John?
Any help is appreciated.
UPDATE:
Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult Create([Bind(Include = "ID,text,subcategory")] Activity codeAC, string term)
{
if (ModelState.IsValid)
{
var result = (from r in db.Activities
where r.subcategory.ToUpper().Contains(term.ToUpper())
select new { r.subcategory }).Distinct();
db.Activities.Add(codeAC);
db.SaveChanges();
return Json(result, JsonRequestBehavior.AllowGet);
}
return Json(codeAC);
}
Script:
<script type="text/javascript">
$(document).ready(function () {
$('#Categories').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Activities/Create",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.subcategory, value: item.subcategory };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
CSHTML:
<div class="form-group">
#Html.LabelFor(model => model.subcategory, htmlAttributes: new { #class = "control-label col-md-2" })
<div class="col-md-10">
#Html.EditorFor(model => model.subcategory, new { htmlAttributes = new { #id = "Categories", #class = "form-control" } })
#Html.ValidationMessageFor(model => model.subcategory, "", new { #class = "text-danger" })
</div>
</div>
I figured it out. I didn't know that I couldn't incorporate this into my Create ActionResult.. so I created a separate JsonResult method and it is working.
Controller:
public JsonResult AutoCompleteCategory(string term)
{
var result = (from r in db.Activities
where r.subcategory.ToUpper().Contains(term.ToUpper())
select new { r.subcategory }).Distinct();
return Json(result, JsonRequestBehavior.AllowGet);
}
SCRIPT:
<script type="text/javascript">
$(document).ready(function () {
$('#Categories').autocomplete({
source: function (request, response) {
$.ajax({
url: "/Activities/AutoCompleteCategory",
type: "POST",
dataType: "json",
data: { term: request.term },
success: function (data) {
response($.map(data, function (item) {
return { label: item.subcategory, value: item.subcategory };
}))
}
})
},
messages: {
noResults: "", results: ""
}
});
})
</script>
Related
I'm a fairly new to JQuery, Json, and MVC. I am trying to a get the autocomplete to work in a text-box (with a drop-down). This is for a parameter value selection used in a web report. The data-table values are in the model called 'BSNList'. THen in the .cshtml View, the BSN text values have to be put to a var for the jquery function to run the autocomplete - I have it working with a inline list to test the autocomplete. But, I can't get the BSNList values to work in the jquery script- even trying with a JsonConvert.SerializeObject here is my code
birthCertificateModel.BSNList = new SelectList(_jobsParamData.AsDataView(), "JobId", "BSN");
birthCertificateModel.JSONresult = JsonConvert.SerializeObject(_jobsParamData);
return View(birthCertificateModel);
<div class="col-md-2">
#*<div class="ui-widget">*#
<label for="tags">BSNs: </label>
<input id="tags" class="ui-autocomplete-input" name="tags">
#*</div>*#
#Html.LabelFor(m => m.BSNName, ReportCaptions.BSN) <br />
#Html.ListBoxFor(m => m.BSNName,
Model.BSNList,
new { #class = "ListBox", size = 8 })
</div>
<script type="text/javascript">
var jsonBSNList;
jsonBSNList = #Model.BSNList.DataTextField;
$(document).ready(function () {
$(function () {
$("#tags").autocomplete({
source: jsonBSNList
});
});
});
`
Figured this out - here is my controller , html and script - I think the ajax is where I stumbled first.
[HttpPost]
public JsonResult SerialNumberLookup(string serialNumberString)
{
using (SqlConnection conn = new SqlConnection(this.connstr))
{
List<string> serialNumberList = new List<string>();
using (SqlCommand cmd =
new SqlCommand(BuildJobStatusModel.LookupSQLSelect, conn))
{
conn.Open();
cmd.Parameters.AddWithValue("#SearchText", serialNumberString);
SqlDataReader sqlDataReader = cmd.ExecuteReader();
while (sqlDataReader.Read())
{
serialNumberList.Add(sqlDataReader["SerialNumber"].ToString());
}
return this.Json(serialNumberList, JsonRequestBehavior.AllowGet);
}
}
<br />
#Html.LabelFor(model => model.SelectedSerialNumber, ReportCaptions.SerialNumber + " Look-up:")
#Html.TextBoxFor(model => model.SelectedSerialNumber, htmlAttributes: new { #id = "autocompleteSerialNumber" })
<br />
$("#autocompleteSerialNumber").autocomplete(
{
minLength: minSearchLen,
source: function (request, response) {
$.ajax({
url: "/Reports/SerialNumberLookup",
type: "POST",
// contentType: "application/json; charset=utf-8",
dataType: "json",
data: { SerialNumberString: request.term },
dataFilter: function (data) { return data; },
success: function (data) {
response($.map(data, function (item) {
return {
value: item
};
}))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
})
}
});
I am using Jquery with Ajax AutoComplete to return some data, but I'm kind of stuck with the display text.
This is what I have:
<script type="text/javascript">
$(document).ready(function () {
$("#locais").autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("CreateF")',
datatype: "json",
data: {
s_localidade: request.term
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.remetente,
value: item.ID,
}
}))
}
})
},
});
});
And on controller:
public JsonResult CreateF(string s_localidade)
{
var tblOficiosExpedidos = db.tblOficiosExpedidos.Include(t => t.tblLocalidades);
var local = (from r in db.tblLocalidades
where r.Remetente.Contains(s_localidade.ToUpper())
select new { remetente = r.Remetente + " - " + r.Cidade, ID = r.LocalidadeID }).ToList();
return Json(local, JsonRequestBehavior.AllowGet);
}
On View:
#Html.TextBox("LocalidadeID","", htmlAttributes: new { #class = "form-control", #id="locais"})
It does work, but when i select an item, the text of the text box becomes the key number from my table. Is there a way to when i select something, the text keep as item.remetente but saves the number of item.ID into table?
You can do with the help of 'select'
try below approach
Your view
#Html.TextBox("LocalidadeID","", htmlAttributes: new { #class = "form-control", #id="locais"})
#Html.Hidden("hiddenlocais")
In your jquery define common function that takes both hidden and text box id as parameters
JQuery:
function WireUpAutoComplete(displayControlId, valueControlId)
{
$(displayControlId).autocomplete({
source: function (request, response) {
$.ajax({
url: '#Url.Action("CreateF")',
datatype: "json",
data: {
s_localidade: request.term
},
select: function (event, ui) {
$(displayControlId).val(ui.item.Remetente);
$(valueControlId).val(ui.item.ID);
return false;
},
success: function (data) {
response($.map(data, function (item) {
return {
label: item.remetente,
value: item.ID,
}
}))
}
})
},
});
}
In document ready call above function
<script type="text/javascript">
$(document).ready(function () {
WireUpAutoComplete("#locais", "#hiddenlocais");
});
</script>
hope this solve your problem. i haven't tested. let me know if you face any problems
Hi I have four fields in my view CustomerName, ContactPerson, Email, MobileNo
CustomerName and ContactPerson are Cascading Dropdown, and Email and MobileNo are textboxes.
If I select the CustomerName, related ContactPerson will load automatically in ContactPerson dropdown.
If I select the Contactperson the Contact person related Email and PhoneNo will load automatically in Email and PhoneNo textbox. This works as expected.
Now all are working fine the two cascading drop down are working fine now my issue is if i select the contact person the contact person related Email and phone no is not displaying in that appropriate text boxes.
My Controller Code:
public JsonResult GetCustomers()
{
return Json(db.Customers.ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetContactPersobByCustomerId(string customerId)
{
Guid Id = Guid.Parse(customerId);
var customercontacts = (from a in db.CustomerContacts where a.CustomerID == Id select a);
return Json(customercontacts, JsonRequestBehavior.AllowGet);
}
public JsonResult GetPhoneNoByContactPersonID(Guid CustomerContactId)
{
var resultMobileNumber = string.Empty;
var resultEmail = string.Empty;
var ContactID = db.CustomerContacts.Where(i => i.CustomerContactID == CustomerContactId).Select(i => i.ContactID).FirstOrDefault();
if (ContactID != null)
{
var contact = (from p in db.Contacts where p.ContactID == ContactID select p).FirstOrDefault();
if (contact != null)
{
if (string.IsNullOrEmpty(contact.Mobile1) == false)
{
resultMobileNumber = contact.Mobile1;
}
else if (string.IsNullOrEmpty(contact.Mobile2) == false)
{
resultMobileNumber = contact.Mobile2;
}
}
if (contact != null)
{
if (string.IsNullOrEmpty(contact.Email1) == false)
{
resultEmail = contact.Email1;
}
else if (string.IsNullOrEmpty(contact.Email2) == false)
{
resultEmail = contact.Email2;
}
}
}
var details = new { success = true, email = resultEmail, mobileno = resultMobileNumber };
return Json(details, JsonRequestBehavior.AllowGet);
}
View Code:
#Html.Label("Customer Name", new { #class = "control-label" })
#Html.DropDownListFor(model => model.CustomerID, new SelectList(string.Empty, "Value", "Text"), "Please select a Customer", new { #class = "form-control required", type = "text" })
#Html.Label("Contact Person", new { #class = "control-label" })
#Html.DropDownListFor(model => model.CustomerContactID, new SelectList(string.Empty, "Value", "Text"), "Please select a ContactPerson", new { #class = "form-control", type = "text", id = "CustomerContactID" })
#Html.LabelFor(model => model.MobileNo, new { #class = "control-label" })
#Html.TextBoxFor(model => model.MobileNo, new { #class = "form-control", type = "text",disabled = "disabled", #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.MobileNo)
#Html.LabelFor(model => model.Email, new { #class = "control-label" })
#Html.TextBoxFor(model => model.Email, new { #class = "form-control", type = "text" ,disabled = "disabled", #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.Email)
J-query Code
<script src="~/Scripts/jquery-ui-1.11.0.js"></script>
<script>
$(function () {
$.ajax(
'#Url.Action("GetCustomers", "VisitorsForm")',{
type: "GET",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.DisplayName + '</option>');
});
}
});
$('#CustomerID').change(function () {
$('#CustomerContactID').empty();
$.ajax(
'#Url.Action("GetContactPersobByCustomerId", "VisitorsForm")',{
type: "POST",
datatype: "Json",
data: { CustomerID: $('#CustomerID').val() },
success: function (data) {
$('#CustomerContactID').append($('<option></option>').val('').text('Please select'));
$.each(data, function (index, value) {
$('#CustomerContactID').append('<option value="' + value.CustomerContactID + '">' + value.ContactReference + '</option>');
});
}
});
});
});
$("#CustomerContactID").change(function () {
alert("hhh");
debugger;
$.ajax(
'#Url.Action("GetPhoneNoByContactPersonID", "VisitorsForm")',{
type: "GET",
dataType: "html",
async: false,
data: { CustomerContactID: $("#CustomerContactID").val()
},
error: function (ex) {
alert('Failed to retrieve Email.' + ex);
},
beforeSend: function () {
},
success: function (data) {
$("#Email").val(data.email);
$("#MobileNo").val(data.mobileno)
alert("Success");
}
});
});
Now all are working fine when i click the contact person it come to the GetPhoneNoByContactPersonID action it calculate the values and return again to the view ans it is also visible in Network too. All are perfect but it not displaying the data in textbox. while i inspect the code it didn't show any error in console. But it shows one warning message which is mentioned below.
Now all are working fine. But i donno why it is not displaying i donno where is the issue is. I tried my level bwst to explain my issue.-please any one help me to clear this issue.
Advance Thanks
There is no id associated with.So assign an id first in TextBoxFor like this.
#Html.TextBoxFor(model => model.MobileNo, new {#id = "MobileNo", #class = "form-control", type = "text",disabled = "disabled", #readonly = "readonly" })
#Html.TextBoxFor(model => model.Email, new {#id = "Email", #class = "form-control", type = "text" ,disabled = "disabled", #readonly = "readonly" })
Now this should work
$("#Email").val(data.email);
$("#MobileNo").val(data.mobileno)
Hi I have four fields in my view: CustomerName, ContactPerson, Email, MobileNo
CustomerName and ContactPerson are Cascading Dropdown, and Email and MobileNo are textboxes.
If I select the CustomerName, related ContactPerson will load automatically in ContactPerson dropdown.
If I select the Contactperson the related Email and PhoneNo will load automatically in Email and PhoneNo textbox. This works as expected.
If I select the CustomerName as "KPM Processing Limited" it loads the ContactPerson ("Mr.Martin") in contact person textbox which is related to CustomerName("KPM Processing Limited"), and if I select the contact person name (Mr.Martin) the contact person related email (kpm#example.com) and phone number (123456) will automatically load in Email and PhoneNo textbox.
Now I select another customerName (e.g. "N.S colors") after selecting ("KPM Processing Limited") and select the contact person name related to "N.S Colors" ("MR.Luthar"). Now Mr.Luthar has mail Id but didn't have phone no so the value of phone no will be null, but it shows the output as Email=luthar24#example.com and phone no =123456.
In other words, when a contact with null phone number is selected, the displayed phone number doesn't become blank as it should.
My Controller Code:
public JsonResult GetCustomers()
{
return Json(db.Customers.ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetContactPersobByCustomerId(string customerId)
{
Guid Id = Guid.Parse(customerId);
var customercontacts = (from a in db.CustomerContacts where a.CustomerID == Id select a);
return Json(customercontacts, JsonRequestBehavior.AllowGet);
}
public JsonResult GetEmailByContactPersonID(Guid CustomerContactId)
{
var ContactID = db.CustomerContacts.Where(i => i.CustomerContactID == CustomerContactId).Select(i => i.ContactID).FirstOrDefault();
var contact1 = (from p in db.Contacts where p.ContactID == ContactID select p).FirstOrDefault().Email1;
if (contact1 == null)
{
var contact2 = (from a in db.Contacts where a.ContactID == ContactID select a).FirstOrDefault().Email2;
contact1 = contact2;
}
return Json(contact1, JsonRequestBehavior.AllowGet);
}
public JsonResult GetPhoneNoByContactPersonID(Guid CustomerContactId)
{
var ContactID = db.CustomerContacts.Where(i => i.CustomerContactID == CustomerContactId).Select(i => i.ContactID).FirstOrDefault();
var mobile1 = (from pn in db.Contacts where pn.ContactID == ContactID select pn).FirstOrDefault().Mobile1;
if (mobile1 == null)
{
var mobile2 = (from a in db.Contacts where a.ContactID == ContactID select a).FirstOrDefault().Mobile2;
mobile1 = mobile2;
}
return Json( mobile1, JsonRequestBehavior.AllowGet);
}
View Code:
#Html.Label("Customer Name", new { #class = "control-label" })
#Html.DropDownListFor(model => model.CustomerID, new SelectList(string.Empty, "Value", "Text"), "Please select a Customer", new { #class = "form-control required", type = "text" })
#Html.Label("Contact Person", new { #class = "control-label" })
#Html.DropDownListFor(model => model.CustomerContactID, new SelectList(string.Empty, "Value", "Text"), "Please select a ContactPerson", new { #class = "form-control", type = "text", id = "CustomerContactID" })
#Html.LabelFor(model => model.MobileNo, new { #class = "control-label" })
#Html.TextBoxFor(model => model.MobileNo, new { #class = "form-control", type = "text",disabled = "disabled", #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.MobileNo)
#Html.LabelFor(model => model.Email, new { #class = "control-label" })
#Html.TextBoxFor(model => model.Email, new { #class = "form-control", type = "text" ,disabled = "disabled", #readonly = "readonly" })
#Html.ValidationMessageFor(model => model.Email)
Jquery Code
<script src="~/Scripts/jquery-ui-1.11.0.js"></script>
<script>
$(function () {
$.ajax(
'#Url.Action("GetCustomers", "VisitorsForm")',{
type: "GET",
datatype: "Json",
success: function (data) {
$.each(data, function (index, value) {
$('#CustomerID').append('<option value="' + value.CustomerID + '">' + value.DisplayName + '</option>');
});
}
});
$('#CustomerID').change(function () {
$('#CustomerContactID').empty();
$.ajax(
'#Url.Action("GetContactPersobByCustomerId", "VisitorsForm")',{
type: "POST",
datatype: "Json",
data: { CustomerID: $('#CustomerID').val() },
success: function (data) {
$('#CustomerContactID').append($('<option></option>').val('').text('Please select'));
$.each(data, function (index, value) {
$('#CustomerContactID').append('<option value="' + value.CustomerContactID + '">' + value.ContactReference + '</option>');
});
}
});
});
});
$("#CustomerContactID").change(function () {
alert("hhh");
$.ajax(
'#Url.Action("GetEmailByContactPersonID", "VisitorsForm")',{
type: "GET",
dataType: "json",
async: false,
data: { CustomerContactID: $("#CustomerContactID").val()
},
error: function (ex) {
alert('Failed to retrieve Email.' + ex);
},
beforeSend: function () {
},
success: function (data) {
$("#Email").val(data);
}
});
});
$("#CustomerContactID").change(function () {
alert("hhh");
$.ajax(
'#Url.Action("GetPhoneNoByContactPersonID", "VisitorsForm")',{
type: "GET",
dataType: "json",
async: false,
data: { CustomerContactID: $("#CustomerContactID").val()
},
error: function (ex) {
alert('Failed to retrieve Email.' + ex);
},
beforeSend: function () {
},
success: function (data) {
$("#MobileNo").val(data);
}
});
});
How can I make the phone field blank when the phone number is null?
If I understand correctly, your problem is when change to a customer who has no phone no, the
MobileNo read only textbox value will not clear.
If my understanding is correct, then your problem lies in your Action GetPhoneNoByContactPersonID()
specificaly, when you are getting mobile1 - the linq query you used was FirstOrDefault().Mobile1,
if it can not be find, null will be returned, and calling Mobile1 in null will result excpetion, resulting nothing pass back from ajax.
hence change your action to something like:
public JsonResult GetPhoneNoByContactPersonID(Guid CustomerContactId)
{
var resultMobileNumber = string.Empty;
var ContactID = db.CustomerContacts.Where(i => i.CustomerContactID == CustomerContactId).Select(i => i.ContactID).FirstOrDefault();
if(ContactID != null)
{
var contact = (from pn in db.Contacts where pn.ContactID == ContactID select pn).FirstOrDefault();
// check if contact is found
if (contact != null)
{
// if mobile 1 has value
if(string.IsNullOrEmpty(contact.Mobile1) == false)
{
resultMobileNumber = contact.Mobile1;
}
else if(string.IsNullOrEmpty(contact.Mobile2) == false)
{
resultMobileNumber = contact.Mobile2;
}
}
}
return Json(resultMobileNumber, JsonRequestBehavior.AllowGet);
}
I have a partial view on a cshtml page as follows :-
#model MvcCommons.ViewModels.CompositeViewModel
#{
ViewBag.Title = "Edit";
}
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Article</legend>
#Html.HiddenFor(model => model.ArticleViewModel.Article.ArticleID)
<div class="editor-label">
#Html.LabelFor(model => model.ArticleViewModel.Article.CategoryID, "Category")
</div>
<div class="editor-field">
#Html.DropDownListFor(model => model.ArticleViewModel.Article.CategoryID, (SelectList)ViewBag.CategoryID)
#Html.ValidationMessageFor(model => model.ArticleViewModel.Article.CategoryID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ArticleViewModel.Article.ArticleTitle)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ArticleViewModel.Article.ArticleTitle)
#Html.ValidationMessageFor(model => model.ArticleViewModel.Article.ArticleTitle)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.ArticleViewModel.Article.ArticleDate)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ArticleViewModel.Article.ArticleDate)
#Html.ValidationMessageFor(model => model.ArticleViewModel.Article.ArticleDate)
</div>
#Html.HiddenFor(model => model.PageViewModel.Page.PageTitle, new { id = "PageTitle" })
#Html.HiddenFor(model => model.PageViewModel.Page.PageAction, new { id = "PageAction" })
#Html.HiddenFor(model => model.ArticleViewModel.Article.ArticleID, new { id = "ArticleID" })
<div class="ImageGallery">
#Html.Partial("~/Views/Shared/ImageGallery.cshtml", Model)
</div>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
The ImageGallery.cshtml Partial View is as follows :-
#model MvcCommons.ViewModels.CompositeViewModel
#{
ViewBag.Title = "Modal image uploader";
}
<script type="text/javascript">
var pageTitle = $('#PageTitle').val();
var pageAction = $('#PageAction').val();
var id = $('#ArticleID').val();
$(document).ready(function () {
$('.modal_block').click(function (e) {
$('#tn_select').empty();
$('.modal_part').hide();
});
$('#modal_link').click(function (e) {
$('.modal_part').show();
var context = $('#tn_select').load('/Upload/UploadImage?Page=' + pageTitle + '&Action=' + pageAction + '&id=' + id, function () {
initSelect(context);
});
e.preventDefault();
return false;
});
$('#delete_images').click(function (e) {
var sList = "";
$('input[type=checkbox]').each(function () {
var sThisVal = (this.checked ? this.value : "");
sList += (sList == "" ? sThisVal : "," + sThisVal);
});
$.ajax({
url: "/Upload/DeleteImages?IDs=" + sList + '&Page=' + pageTitle + '&Action=' + pageAction + '&id=' + id,
data: sList,
cache: false,
type: "POST",
dataType: "json"
});
reloadGallery();
return false;
});
function reloadGallery() {
$.ajax({
type: "GET",
url: '/Upload/Index/',
data: "{}",
cache: false,
dataType: "html",
success: function (data)
{ $().html(data); }
})
}
});
</script>
<div class="modal_block modal_part"></div>
<div class="modal_dialog modal_part" id="tn_select"></div>
<h2>List of images</h2>
<p>
This page contains the list of all uploaded images.
</p>
#if (Model.ImageViewModel.Images.Count > 0)
{
<div class="imageContainer">
<div class="div-table">
<div class="div-table-row-title">
<div class="div-table-col">Image</div>
<div class="div-table-col">Image Name</div>
</div>
</div>
}
</div>
<div class="DeleteImages">
Delete Selected Images.
</div>
}
else
{
<div class="imageCenter">
No images have been uploaded so far.
</div>
}
<p>
Click here to open modal dialog.
</p>
<div class="clear"></div>
Here is the code in the Controller to delete the images:-
[HttpPost]
public ActionResult DeleteImages(string IDs)
{
_Page = Request.QueryString["Page"];
_Action = Request.QueryString["Action"];
_ItemID = Convert.ToInt32(Request.QueryString["id"]);
Generics.PageIDS currentPage = (Generics.PageIDS)Enum.Parse(typeof(Generics.PageIDS), _Page);
_PageID = Convert.ToInt32(currentPage);
string[] sepImageIds = IDs.Split(',');
foreach (string strImageId in sepImageIds)
{
imageViewModel.DeleteFromXML(strImageId);
}
return RedirectToAction(_Action, _Page, new { id = _ItemID });
}
Everything works fine in this Partial View, except for when I delete an image, the deletion is done correctly, however when the code is passed back to the View, the Partial View is not refreshed.
Is there something I am missing?
Thanks for your help and time!
------------------UPDATE---------------------------------------------
This is the Edit Controller Action after the Delete has finished :-
public ActionResult Edit(int id = 0)
{
articleViewModel.Article = unitOfWork.ArticleRepository.GetByID(id);
pageViewModel.Page.PageTitle = "Article";
pageViewModel.Page.PageAction = "Edit";
if (articleViewModel.Article == null)
{
return HttpNotFound();
}
PopulateDropDownList(articleViewModel.Article.CategoryID);
viewModel.ArticleViewModel = articleViewModel;
int ImageCount = 0;
imageViewModel.Images = imageViewModel.PopulateFromXML(pageViewModel.GetPageID(_PageName), id, out ImageCount).ToList();
viewModel.ImageViewModel = imageViewModel;
viewModel.PageViewModel = pageViewModel;
return View(viewModel);
//return Json(viewModel, JsonRequestBehavior.AllowGet);
}
I think it is because all partial views are cached by default, what I would do is to create a method in the controller to return an ActionResult like so, with the output cache attribute of 0, so it does not cache
[OutputCache(Duration = 0)]
public ActionResult ImageGalleryAction()
{
// do return your cshtml name here
return PartialView("ImageGallery");
}
I would give an id to your imageGalleryDiv, change your reloadGallery method to load the partial view on onload event as well and remove the #Html.Partial like so
<script>
function reloadGallery(){
$('#myImageGallery').load("ImageGalleryAction");
}
</script>
<div id="myImageGallery" class="ImageGallery" onload="reloadGallery()">
</div>
That way, your partial view will be manually injected/refreshed via jquery and it won't be cached.
Cheers
You need to call the reloadGallery function once your DELETE ajax call succeeds, which is inside the success callback:
$.ajax({
url: '/Upload/DeleteImages?IDs=' + sList + '&Page=' + pageTitle + '&Action=' + pageAction + '&id=' + id,
data: sList,
cache: false,
type: 'POST',
success: function(data) {
reloadGallery();
}
});
Not to mention that your DeleteImages action doesn't return any JSON, so you should remove the dataType: 'json' switch. You seem to be redirecting at the end of the DeleteImages action. Are you sure that you are redirecting to a controller action that returns a partial?
Also instead of firing yet another AJAX request in your reloadGallery method why not simply have your DeleteImages action return the partial and inside the success call update the corresponding section of your DOM using the .html method?
I think it might be in your ajax call
function reloadGallery() {
$.ajax({
type: "GET",
url: '/Upload/Index/',
data: "{}",
cache: false,
dataType: "html",
success: function (data)
{ $().html(data); }
})
}
remove the data: "{}" or replace it with data: {}