Removing a Partial View in MVC - asp.net-mvc-3

I have a View with Name, CreatedDate, Address, etc. In the Address section I have State, City etc. I made this section a Partial View.
By default there will be one address section in mainView. I have a button "AddAddress". I want to add another address section if user clicks the button (add a partial view). After getting this partial view there should be a remove button to remove this partial view. I am not using Razor.
the following code is my Javascript to delete my address.
function deleteAddress(addressId, clientId) {
var url1 = "/Client/DeleteAddress";
if (confirm("Are you sure you want to delete this address?")) {
var result = false;
$.ajax({
url: url1,
type: 'POST',
async: false,
data: { AddressId: addressId, ClientId: clientId },
dataType: 'json',
success: function (data) {
result = data;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest=" + XMLHttpRequest.responseText + "\ntextStatus=" + textStatus + "\nerrorThrown=" + errorThrown);
}
});
if (result) {
}
}
}
the following code is in my controller.
[HttpPost]
public JsonResult DeleteAddress(int AddressId, int ClientId)
{
if (AddressId != 0)
{
if (ClientId != 0)
{
ClientService.Client clientVuTemp = new ClientService.Client();
clientVuTemp = (ClientService.ClientView)TempData["EditClientData"];
clientVuTemp.Address.RemoveAt(AddressId);
//soft delete
clientVuTemp.Address[AddressId].IsActive = false;
_clientSvc.InserOrUpdateClientAddresses(clientVuTemp.Address);
}
else
{
}
return Json(true);
}
else
return Json(false);
}

In the Model we can have a property like IsAddAddressEnabled, Onclick on AddAddress you can set this as true and onclick on cancel you can set as false.
In View you can put an condition,
#if(Model.IsAddAddressEnabled)
{
Html.Partail(....)
}

Related

jqueryui autocomplete render HTML returned by server

I have a simple page with an input text-box. The text box is bound to jquery ui autocomplete that makes an AJAX call to the server. My server side code is an ASP.NET MVC site. The only difference I have as compared to most examples found over the Internet is that my Server side code returns a PartialView (html code) as results instead of JSON. I see the AJAX call happening and I see the HTML response in the AJAX success event as well.
My question is how do I bind this HTML data to show in the AutoComplete?
The code I have so far is:
$("#quick_search_text").autocomplete({
minLength: 3,
html: true,
autoFocus: true,
source: function (request, response) {
$.ajax({
type: "POST",
url: "serversideurl",
data: "{ 'SearchTerm': '" + request.term + "', 'SearchCategory': '" + $("#quick_search_category").val() + "' }",
contentType: "application/json; charset=utf-8",
dataType: "html",
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
},
success: function (data) {
//THIS IS WHERE MY HTML IS RETURNED FROM SERVER SIDE
//HOW DO I BIND THIS TO JQUERY UI AUTOCOMPLETE
}
});
},
select: function (event, ui) {
},
response: function (event, ui) {
console.log(ui);
console.log(event);
}
});
This works:
1) Create an action in your controller and set the RouteConfig to start this action
public class HomeController : Controller
{
public ActionResult Index20()
{
MyViewModel m = new MyViewModel();
return View(m);
}
Create a view without any type of master page
Add this view model:
public class MyViewModel
{
public string SourceCaseNumber { get; set; }
}
Go to Manage Nuget Packages or PM Console and add to MVC 5 project - Typeahead.js for MVC 5 Models by Tim Wilson
Change the namespace for the added HtmlHelpers.cs to System.Web.Mvc.Html and rebuild
Add this class:
public class CasesNorm
{
public string SCN { get; set; }
}
Add these methods to your controller:
private List<Autocomplete> _AutocompleteSourceCaseNumber(string query)
{
List<Autocomplete> sourceCaseNumbers = new List<Autocomplete>();
try
{
//You will goto your Database for CasesNorm, but if will doit shorthand here
//var results = db.CasesNorms.Where(p => p.SourceCaseNumber.Contains(query)).
// GroupBy(item => new { SCN = item.SourceCaseNumber }).
// Select(group => new { SCN = group.Key.SCN }).
// OrderBy(item => item.SCN).
// Take(10).ToList(); //take 10 is important
CasesNorm c1 = new CasesNorm { SCN = "11111111"};
CasesNorm c2 = new CasesNorm { SCN = "22222222"};
IList<CasesNorm> aList = new List<CasesNorm>();
aList.Add(c1);
aList.Add(c2);
var results = aList;
foreach (var r in results)
{
// create objects
Autocomplete sourceCaseNumber = new Autocomplete();
sourceCaseNumber.Name = string.Format("{0}", r.SCN);
sourceCaseNumber.Id = Int32.Parse(r.SCN);
sourceCaseNumbers.Add(sourceCaseNumber);
}
}
catch (EntityCommandExecutionException eceex)
{
if (eceex.InnerException != null)
{
throw eceex.InnerException;
}
throw;
}
catch
{
throw;
}
return sourceCaseNumbers;
}
public ActionResult AutocompleteSourceCaseNumber(string query)
{
return Json(_AutocompleteSourceCaseNumber(query), JsonRequestBehavior.AllowGet);
}
credit goes to http://timdwilson.github.io/typeahead-mvc-model/

ajax calls the mvc controller

why this code does not work?.I receive "ok" but i can not see the view1 (view1 not loaded).I want to manage the views by prop1 .If the value of prop1="1" load view1
Hier is my controller
[System.Web.Mvc.Route("Home/SubmitMyData/")]
[System.Web.Http.HttpPost]
public ActionResult SubmitMyData([FromBody]MyParamModel mydata)
{
if (mydata.Prop1.Equals("1"))
return View("veiw1");
else
return View("view2");
}
public class MyParamModel // #4
{
public string Prop1 { get; set; }
public string Prop2 { get; set; }
}
and it is my ajax call
$('#Buttonv').click(function () {
var myData = {Prop1: "1", Prop2: ""}; // #1
$.ajax({
type: 'POST',
data: myData, // #2
url: '/Home/SubmitMyData',
})
.success(function (data) {
var output = "ok";
$('#lblmessage').html(output);
})
.error(function (xhr, ajaxoption, thrownError) {
$('#lblmessage').html("moshkelo" + xhr + "ajaxoption= " + ajaxoption + " throwerror=" + thrownError);
});
//return false;
});
If you are returning a View from your Controller, you'll need to ensure that you are actually using the HTML content within the success callback of your POST :
.success(function (data) {
// data will contain your content
$('#lblmessage').html(data);
})
You were previous using output, which didn't seem to be defined anywhere within your script.
Additionally, you may want to check the name of the view that you are returning as return View("veiw1"); seems like a typo that should be return View("View1");.
In your javascript, you are ignoring the HTML returned by the server. Try changing it to...
.success(function (data) {
$('#lblmessage').html(data);
})
Per the documentation, the first parameter to the success method is the data returned by the server.

Not getting Json object (having a collection) correctly in controller using ajax call

I am sending a json object to controller via ajax call, data property of ajax call showing correct data. On post to controller's method -received parameter having collection and its count is showing perfectly but the properties inside the collection is not showing values.
Here is the code -
Controller-
[HttpPost]
public ActionResult ImageOperations(ImageProcessingModel imageProcessingModel)
{
return Json("sucess");
}
Model-
public class ImageProcessingModel
{
public string Source { get; set; }
private List<ThumbnailImageSubTaskModel> _thumbnailImageSubTaskModel;
public List<ThumbnailImageSubTaskModel> ThumbnailImageSubTaskModel
{
get
{
if (_thumbnailImageSubTaskModel == null)
{
_thumbnailImageSubTaskModel = new List<ThumbnailImageSubTaskModel>();
}
return _thumbnailImageSubTaskModel;
}
}
}
js-
var ImageProcessingModel =
{
"Source": "test",
"ThumbnailImageSubTaskModel":allThumbnails.allItems()
}
allThumnails.allItems is ko.observableArray() which having values.
$.ajax({
url: '/ImageProcessingTask/ImageOperations',
type: 'Post',
data: ImageProcessingModel,
success: function (data, status) {
processEscapeKeyPress = true;
var fn = window[successCallback];
fn(data, passDataToCallback);
},
error: function (xhr, desc, err) {
alert(err);
processEscapeKeyPress = true;
processAjaxError(xhr, desc, err);
},
});
here ImageProcessingModel having all values and source is simple a string so this value is coming in the controller only the ThumbnailImageSubTaskModel showing counts but not its value.
Thanks!!
A common problem encoutered with sending JSON through AJAX to MVC. Many forget to set the type of data in their AJAX request.
Try setting the datatype and contentType:
$.ajax({
url: '/ImageProcessingTask/ImageOperations',
type: 'Post',
**contentType: 'application/json; charset=UTF-8',
dataType: 'json',**
data: ImageProcessingModel,
success: function (data, status) {
processEscapeKeyPress = true;
var fn = window[successCallback];
fn(data, passDataToCallback);
},
error: function (xhr, desc, err) {
alert(err);
processEscapeKeyPress = true;
processAjaxError(xhr, desc, err);
},
});

Send to and get value from a MVC3 controller by AJAX

I have a html input text field and a button.
I want to take user input value from that html text field by clicking that button and want to send that value (by AJAX) into a MVC3 Controller ( as like as a parameter of an ActionResult setValue() ) ?
An other thing i want to know that, how i can get a return value (that return by a ActionResult getValue() ) from a MVC3 Controller and set it in a html text field (by AJAX) ?
please help me with a good example, please. and sorry for my bad English. :)
Button click event
$(document).ready(function ()
{
$('#ButtonName').click(function ()
{
if ($('#YourHtmlTextBox').val() != '')
{
sendValueToController();
}
return false;
});
});
You call your ajax function like so:
function sendValueToController()
{
var yourValue = $('#YourHtmlTextBox').val();
$.ajax({
url: "/ControllerName/ActionName/",
data: { YourValue: yourValue },
cache: false,
type: "GET",
timeout: 10000,
dataType: "json",
success: function (result)
{
if (result.Success)
{ // this sets the value from the response
$('#SomeOtherHtmlTextBox').val(result.Result);
} else
{
$('#SomeOtherHtmlTextBox').val("Failed");
}
}
});
}
This is the action that is being called
public JsonResult ActionName(string YourValue)
{
...
return Json(new { Success = true, Result = "Some Value" }, JsonRequestBehavior.AllowGet);
}

Passing jquery object to MVC action

I am trying to use .ajax() to post a People object to a MVC2 action that expects a ViewModel as parameter. The ViewModel has a People property.
The problem is that when the MVC action is activated, the ajax() postback People object is always null. I used Fiddler to diagnose the problem. The property values in the People object are all contained in the header. Here is my client jQuery script. Please note that I used three methods to stuff the property values into People object, but none of them works.
StaffDlg.delegate("#SaveButton", "click",
function (e) {
e.preventDefault();
People["PKey"] = $("#PKey").val();
People["FName"] = $("#FName").val();
People["LName"] = $("#LName").val();
People["MName"] = $("#MName").val();
People["SSN"] = $("#SSN").val();
People["Gender"] = $("#Gender").val();
People["DOB"] = $("#DOB").val();
People["BirthPlace"] = $("#BirthPlace").val();
People["NetworkAccount"] = $("#NetworkAccount").val();
var pkey = $("#PKey").val();
var action;
if (!isNaN(parseFloat(pkey)) && isFinite(pkey)) {
action = "Edit" + "/" + pkey;
}
else {
action = "Create";
}
$.ajax({
url: getRootUrl() + "/Staff/" + action,
//data: { FName: $("#FName").val(), LName: $("#LName").val(), MName: $("#MName").val(),
// SSN: $("#SSN").val(), Gender: $("#Gender").val(), DOB: $("#DOB").val(),
// BirthPlace: $("#BirthPlace").val(), NetworkAccount: $("#NetworkAccount").val()
//},
//data: JSON.stringify(People),
data: $("Form").serialize(),
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
success: function (result) {
$("#ajaxResponse").addClass("whiteOnGreen").html("Update succeeded");
},
error: function (qXHR, textStatus, errorThrown) {
$("#ajaxResponse").addClass("whiteOnRed").html("Failed to save the record!\r\n" +
textStatus + ": " + errorThrown + "\r\n" +
"data : " + JSON.stringify(People));
}
})
}
);
and here is the MVC action.
public ActionResult Edit(int id, StaffViewModel updatedStaff)
{
People staff = _staffService.GetStaff(id);
if (updatedStaff == null)
return View("NotFound");
if (ModelState.IsValid)
{
TryUpdateModel<People>(staff, "staff");
staff.RecordLastUpdated = DateTime.Now;
staff.UpdatedBy = HttpContext.User.Identity.Name;
_staffService.SaveStaff();
//return RedirectToAction("Index", new { id = thisStaff.PKey });
if (Request.IsAjaxRequest())
return this.Json(staff, JsonRequestBehavior.AllowGet);
else
{
if (string.IsNullOrEmpty(updatedStaff.previousURL))
return Redirect("/Staff/Startwith/" + staff.LName.Substring(1, 1));
else
return Redirect(updatedStaff.previousURL);
}
}
else
{
if (Request.IsAjaxRequest())
{
string errorMessage = "<div class='whiteOnRed error'>"
+ "The following errors occurred:<ul>";
foreach (var key in ModelState.Keys)
{
var error = ModelState[key].Errors.FirstOrDefault();
if (error != null)
{
errorMessage += "<li>"
+ error.ErrorMessage + "</li>";
}
}
errorMessage += "</ul></div>";
return Json(new { Message = errorMessage });
}
else
return View(updatedStaff);
}
}
You state that the form expects a StaffViewModel as a parameter, and a StaffViewModel has a People property... but you are not passing the full StafFViewModel object - instead you are passing a People object from the Ajax call, and hoping that the People property gets populated on the MVC end.
There is a disconnect there and the auto-binder doesn't know how to bridge it.
Try creating a controller method with a (int, People) signature, and see if that works for you.
Otherwise, you might need to create a custom binder.
Try removing dataType and contentType settings from your ajax call:
$.ajax({
url: getRootUrl() + "/Staff/" + action,
data: $("Form").serializeArray(),
type: "POST",
success: function (result) {
$("#ajaxResponse").addClass("whiteOnGreen").html("Update succeeded");
},
error: function (qXHR, textStatus, errorThrown) {
$("#ajaxResponse").addClass("whiteOnRed").html("Failed to save the record!\r\n" +
textStatus + ": " + errorThrown + "\r\n" +
"data : " + JSON.stringify(People));
}
})
I solved the problem with the .ajax() not posting the form values to the MVC Create(People person) action. It was the parameter type that this different than the one used in Edit(StaffViewModel). Now both action accept the same type of parameter, StaffViewMode.

Resources