I got stucked with (it seems to be) a simple problem.
My goal is to create a modal with an Ajax form. A child action gets the modal in a partial view, and when edited, submit button posts Ajax form which returns just Json data. Built-in code in Ajax.BeginForm should trigger OnSuccess or OnFailure depending on the result of the action.
The problem is OnFailure is triggered and OnSuccess don't, although the action finishes OK, and post return a 200 code. The "data" param in OnFailure function contains the HTML of the whole page.
This is the code:
(1) Snippet to load the modal in the main view:
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
#Html.Action("GetDialogV2", "Fianzas", new { idArrendamiento = Model.Id_Arrendamiento })
</div>
(2) Button to open the modal in the main view:
<button type="button" class="btn btn-outline-primary" data-toggle="modal" data-target="#exampleModal">
<i class="far fa-hand-holding-usd"></i> Modal
</button>
(3) The partial view with the modal (and the Ajax Form), GetDialogV2.cshtml:
#model EditFianzas_vm
#{
AjaxOptions ajaxOptions = new AjaxOptions
{
HttpMethod = "POST",
UpdateTargetId = "Respuesta",
OnSuccess = "OnSuccess",
OnFailure = "OnFailure"
};
}
#using (Ajax.BeginForm(ajaxOptions))
{
#Html.AntiForgeryToken()
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Fianza</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="form-horizontal">
#Html.ValidationSummary(true)
#Html.HiddenFor(model => model.Id_Arrendamiento)
<div class="form-group">
#Html.LabelFor(model => model.Importe, new { #class = "control-label col-md-6" })
<div class="col-md-8">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-euro-sign"></i></span>
</div>
#Html.EditorFor(model => model.Importe, new { htmlAttributes = new { #class = "form-control importe" } })
</div>
#Html.ValidationMessageFor(model => model.Importe, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
#Html.LabelFor(model => model.Fecha_Abono, new { #class = "control-label col-md-6" })
<div class="col-md-8">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text"><i class="far fa-calendar"></i></span>
</div>
#Html.TextBoxFor(model => model.Fecha_Abono, "{0:dd/MM/yyyy}", new { #class = "form-control datepicker" })
</div>
#Html.ValidationMessageFor(model => model.Fecha_Abono, "", new { #class = "text-danger" })
</div>
</div>
<div class="form-group">
<div class="col-md-8">
<input type="text" id="Respuesta" class="form-control" />
</div>
</div>
</div>
</div>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancelar</button>
<button type="submit" class="btn btn-primary" id="botonPrueba">Guardar</button>
</div>
</div>
<!-- /.modal-content -->
</div>
}
(4) The Javascript in the main view:
#section scripts
{
<script type="text/javascript">
function OnSuccess(data) {
if (data.Success == true) {
toastr.success("Operación realizada.", "Fianzas");
$("#exampleModal").modal('hide');
}
else {
if (data.modelState) {
$.each(d.modelState, function (i, item) {
toastr.info(i + ': ' + item, "i: item");
//item.valid(); //run jQuery validation to display error
$('#' + i).valid();
});
}
else {
toastr.error(data.Error, "Fianzas");
}
}
}
function OnFailure(data) {
alert(data);
alert('HTTP Status Code: ' + data.param1 + ' Error Message: ' + data.param2);
toastr.error("Se ha producido un error no controlado al realizar la operación.", "Fianzas");
toastr.warning(data, "Fianzas");
}
</script>
}
(5) And finally, the controller:
#region Ajax Form (GetDialogV2)
public PartialViewResult GetDialogV2(int idArrendamiento)
{
//Obtengo el modelo...
Arrendamientos_Fianzas fianza = db.Arrendamientos_Fianzas.Find(idArrendamiento);
//Creo la vista-modelo...
EditFianzas_vm vm = new EditFianzas_vm {
Id_Arrendamiento = idArrendamiento,
Importe = fianza.Importe,
Fecha_Abono = fianza.Fecha_Abono
};
return PartialView(vm);
}
[HttpPost]
[ValidateAntiForgeryToken]
public JsonResult GetDialogV2(EditFianzas_vm vm)
{
try
{
if (!ModelState.IsValid)
{
var modelState = ModelState.ToDictionary
(
kvp => kvp.Key,
kvp => kvp.Value.Errors.Select(e => e.ErrorMessage).ToArray()
);
modelState.Add("hdId_Arrendamiento", modelState["vm.Id_Arrendamiento"]);
modelState.Remove("vm.Id_Arrendamiento");
modelState.Add("txtImporte", modelState["vm.Importe"]);
modelState.Remove("vm.Importe");
modelState.Add("txtFecha_Abono", modelState["vm.Fecha_Abono"]);
modelState.Remove("vm.Fecha_Abono");
return Json(new { modelState }, JsonRequestBehavior.AllowGet);
//throw (new Exception("Error en la validación del modelo."));
}
//Miro a ver si existen datos para este arrendamiento (no sé si es un edit o un new, si quiero hacerlo todo en una misma acción)
Arrendamientos_Fianzas fianza = db.Arrendamientos_Fianzas.Find(vm.Id_Arrendamiento);
//Compruebo si es nuevo o editado...
if (fianza == null)
{
//Nuevo registro...
fianza = new Arrendamientos_Fianzas
{
Id_Arrendamiento = vm.Id_Arrendamiento,
Importe = vm.Importe,
Fecha_Abono = vm.Fecha_Abono
};
//Actualizo info de control...
fianza.C_Fecha = DateTime.Now;
fianza.C_IdUsuario = Usuario.NombreUsuario;
fianza.C_Comentarios = "Alta de la fianza.";
//Guardo registro...
db.Arrendamientos_Fianzas.Add(fianza);
}
else
{
//Estoy editando, grabo valores...
fianza.Importe = vm.Importe;
fianza.Fecha_Abono = vm.Fecha_Abono;
//Actualizo info de control...
fianza.C_Fecha = DateTime.Now;
fianza.C_IdUsuario = Usuario.NombreUsuario;
fianza.C_Comentarios = "Modificación de los datos de la fianza.";
//Modifico estado del registro en el modelo...
db.Entry(fianza).State = EntityState.Modified;
}
//Guardo cambios...
db.SaveChanges();
//Return...
return new JsonResult() { Data = Json(new { Success = true }) };
}
catch (Exception ex)
{
return new JsonResult() { Data = Json(new { Success = false, Error = ex.Message }) };
}
}
#endregion
Thanks a lot in advance for your time and help.
Best regards,
Fernando.
I got it. It was a subtle solution, as I barely guessed:
If Javascript is disabled, or in certain circumstances, you need to explicitly pass action to the AjaxOptions, like that:
AjaxOptions ajaxOptions = new AjaxOptions()
{
HttpMethod = "POST",
OnSuccess = "OnSuccess(data)",
OnFailure = "OnFailure",
OnBegin = "OnBegin",
OnComplete = "OnComplete",
Url = Url.Action("GetDialogV2")
};
Related
I created a form. I want to do a post save method.
He records but records the same data twice. How can I solve this problem?
I have to solve the double registration problem. I'm pushing the button once. When I go through Debug step by step, it goes twice on the same line. When I control the db as a top-down, I see that you double-logged.
HTML:
<div class="portlet-body form">
#using (Ajax.BeginForm("TalepTurKaydet", "MasterEducationController",
new AjaxOptions { HttpMethod = "post", OnSuccess = "TalepTurKaydet" },
new { #class = "" }))
{
#Html.ValidationSummary(true)
<div class="form-body">
<div class="row">
<div class="col-md-12" style="margin-left: 20px">
<div class="col-md-6">
<div class="form-group">
<label class="control-label col-md-3">Açıklama: </label>
<div class="col-md-9">
<textarea id="Aciklama" name="Aciklama" class="col-md-12" style="resize: none;" rows="5" placeholder="Açıklama"></textarea>
</div>
</div>
</div>
<div class="clearfix"></div><br /><br />
</div>
<div class=" form-actions right">
<button type="button" class="btn green btnPrevious"><i class="fa fa-angle-double-left"></i>Geri</button>
<button id="talepOlustur" type="submit" class="btn blue"><i class="fa fa-check"></i> Talep Oluştur</button>
</div>
</div>
}
</div>
Controller:
public ActionResult MezuniyetBilgiKaydet(MezuniyetBilgi model)
{
List<MezuniyetBilgi> list = null;
model.KullaniciId = GetUye().kullaniciID;
using (var client = new HttpClient())
{
client.BaseAddress = new Uri(ApiAdress.API_URL);
var responseTask = client.PostAsJsonAsync("apiMasterProgramEducation/MezuniyetBilgiKaydet", model);
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var readTask = result.Content.ReadAsAsync<List<MezuniyetBilgi>>();
readTask.Wait();
list = readTask.Result;
model = list.FirstOrDefault();
return Json(new
{
Success = true,
data = model,
Message = SuccessMessage.MEZUNIYET_BILGISI_INSERT_MESSAGE,
JsonRequestBehavior.AllowGet
});
}
}
}
API:
public IHttpActionResult MezuniyetBilgiKaydet(MezuniyetBilgi model)
{
List<MezuniyetBilgi> detay = new List<MezuniyetBilgi>();
try
{
using (var ctx = new ktdbEntities())
{
if (model != null)
{
var query = ctx.mezuniyetBilgisiEkle(model.KullaniciId, model.MezuniyetTarih, model.MezunOlduguOkul,
model.MezunOlduguFakulte, model.MezunOlduguBolum, (float)(model.MezuniyetNotu));
model.Output = true;
detay.Add(model);
return Ok(detay);
}
}
}
catch (Exception e)
{
model.Output = false;
model.Message = e.Message;
detay.Add(model);
}
return Ok(detay);
}
I have implemented a code to create Tree View and also save it into database.
Controller
public ActionResult IndexMda()
{
using (BackendEntities context = new BackendEntities())
{
var plist = context.MDA.Where(p => p.PARENT_MDA_ID == null).Select(a => new
{
a.MDA_ID,
a.MDA_NAME,
a.MDA_DESCRIPTION,
a.ORGANIZATION_TYPE
}).ToList();
ViewBag.plist = plist;
}
GetHierarchy();
return View();
}
public JsonResult GetHierarchy()
{
List<MDA2> hdList;
List<MdaViewModel> records;
using (BackendEntities context = new BackendEntities())
{
hdList = context.MDA.ToList();
records = hdList.Where(l => l.PARENT_MDA_ID == null)
.Select(l => new MdaViewModel
{
MDA_ID = l.MDA_ID,
text = l.MDA_NAME,
MDA_DESCRIPTION = l.MDA_DESCRIPTION,
ORGANIZATION_TYPE = l.ORGANIZATION_TYPE,
PARENT_MDA_ID = l.PARENT_MDA_ID,
children = GetChildren(hdList, l.MDA_ID)
}).ToList();
}
return this.Json(records, JsonRequestBehavior.AllowGet);
// return View();
}
private List<MdaViewModel> GetChildren(List<MDA2> hdList, long PARENT_MDA_ID)
{
return hdList.Where(l => l.PARENT_MDA_ID == PARENT_MDA_ID)
.Select(l => new MdaViewModel
{
MDA_ID = l.MDA_ID,
text = l.MDA_NAME,
MDA_DESCRIPTION = l.MDA_DESCRIPTION,
ORGANIZATION_TYPE = l.ORGANIZATION_TYPE,
PARENT_MDA_ID = l.PARENT_MDA_ID,
children = GetChildren(hdList, l.MDA_ID)
}).ToList();
}
[HttpPost]
public JsonResult ChangeNodePosition(long MDA_ID, long PARENT_MDA_ID)
{
using (BackendEntities context = new BackendEntities())
{
var Hd = context.MDA.First(l => l.MDA_ID == MDA_ID);
Hd.PARENT_MDA_ID = PARENT_MDA_ID;
context.SaveChanges();
}
return this.Json(true, JsonRequestBehavior.AllowGet);
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddNewNode(AddNode model)
{
try
{
if (ModelState.IsValid)
{
using (BackendEntities db = new BackendEntities())
{
MDA2 hierarchyDetail = new MDA2()
{
MDA_NAME = model.NodeName,
PARENT_MDA_ID = model.ParentName,
MDA_DESCRIPTION = model.NodeDescription,
ORGANIZATION_TYPE = model.NodeOrganizationType
};
db.MDA.Add(hierarchyDetail);
db.SaveChanges();
}
return Json(new { success = true }, JsonRequestBehavior.AllowGet);
}
}
catch (Exception ex)
{
throw ex;
}
return Json(new { success = false }, JsonRequestBehavior.AllowGet);
}
The partial view is where the Tree View is created
Partial View
#model BPP.CCSP.Admin.Web.ViewModels.AddNode
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button"
class="close"
data-dismiss="modal"
aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title">Add Node</h4>
</div>
<div class="modal-body">
#using (Html.BeginForm("AddNewNode", "Mda", FormMethod.Post, new { #id = "formaddNode", #class = "form-horizontal", role = "form", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="col-md-12">
<div class="col-md-6 row">
<div class="input-group">
<input type="text" class="form-control" value="Perent Node" readonly="readonly">
<span class="input-group-addon">
#Html.RadioButtonFor(model => model.NodeTypeRbtn, "Pn", new { #class = "btn btn-primary rbtnnodetype" })
</span>
</div>
</div>
<div class="col-md-6">
<div class="input-group ">
<input type="text" class="form-control" value="Child Node" readonly="readonly">
<span class="input-group-addon">
#Html.RadioButtonFor(model => model.NodeTypeRbtn, "Cn", new { #class = "rbtnnodetype" })
</span>
</div>
</div>
<br />
#Html.ValidationMessageFor(m => m.NodeTypeRbtn, "", new { #class = "alert-error" })
</div>
<div class="clearfix">
</div>
<div class="col-md-12">
<div class="petenddiv hidden">
#Html.Label("Select Parent")
#Html.DropDownList("ParentName", new SelectList(ViewBag.plist, "MDA_ID", "MDA_NAME"), "--select--", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.ParentName, "", new { #class = "alert-error" })
</div>
</div>
<div class="clearfix">
</div>
<div class="col-md-12">
<div>
#Html.Label("MDA Name")
#Html.TextBoxFor(model => model.NodeName, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.NodeName, "", new { #class = "alert-error" })
</div>
</div>
<div class="col-md-12">
<div>
#Html.Label("Description")
#Html.TextBoxFor(model => model.NodeDescription, new { #class = "form-control" })
#Html.ValidationMessageFor(model => model.NodeDescription, "", new { #class = "alert-error" })
</div>
</div>
<div class="col-md-12">
<div>
#Html.Label("Organization Type")
#Html.DropDownListFor(model => model.NodeOrganizationType, new List<SelectListItem>
{
new SelectListItem{Text = "Agency", Value = "Agency"},
new SelectListItem{Text = "Commission", Value = "Commission"},
new SelectListItem{Text = "Department", Value = "Department"},
new SelectListItem{Text = "Ministry", Value = "Ministry"}
}, "Select Error Type", new { #style = "border-radius:3px;", #type = "text", #class = "form-control", #placeholder = "Enter Organization Type", #autocomplete = "on" })
#Html.ValidationMessageFor(model => model.NodeDescription, "", new { #class = "alert-error" })
</div>
</div>
<div class="clearfix">
</div>
<br />
<br />
<div class="col-md-12">
<div>
<div class="pull-left">
<input type="submit" id="savenode" value="S A V E" class="btn btn-primary" />
</div>
<div class="pull-right">
<input type="button" id="closePopOver" value="C L O S E" class="btn btn-primary" />
</div>
</div>
</div>
<div class="clearfix">
</div>
}
</div>
</div>
View
<div class="col-md-12" style="margin:100px auto;">
<div class="modal fade in" id="modalAddNode" role="dialog" aria-hidden="true">
#Html.Partial("_AddNode")
</div>
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">Ministries, Departments and Agencies -: [ Add MDA and its Members ]</div>
<div class="panel-body">
<div id="tree"></div>
<div class="clearfix">
</div>
<br />
<div>
<button id="btnDeleteNode" data-toggle="modal" class='btn btn-danger'> Delete Node <span class="glyphicon glyphicon-trash"></span> </button>
<button id="btnpopoverAddNode" data-toggle="modal" class='btn btn-warning'> Add Node <span class="glyphicon glyphicon-plus"></span> </button>
</div>
</div>
</div>
</div>
Scipts
#section Scripts {
#System.Web.Optimization.Scripts.Render("~/bundles/jqueryval")
<script src="#Url.Content("~/Scripts/conditional-validation.js")" type="text/javascript"></script>
<script src="~/Scripts/Gijgo/gijgo.js"></script>
<link href="http://code.gijgo.com/1.3.0/css/gijgo.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
//'Hierarchy/GetHierarchy'
$(document).ready(function () {
var Usertree = "";
var tree = "";
$.ajax({
type: 'get',
dataType: 'json',
cache: false,
url: '/Mda/GetHierarchy',
success: function (records, textStatus, jqXHR) {
tree = $('#tree').tree({
primaryKey: 'MDA_ID',
dataSource: records,
dragAndDrop: true,
checkboxes: true,
iconsLibrary: 'glyphicons',
//uiLibrary: 'bootstrap'
});
Usertree = $('#Usertree').tree({
primaryKey: 'MDA_ID',
dataSource: records,
dragAndDrop: false,
checkboxes: true,
iconsLibrary: 'glyphicons',
//uiLibrary: 'bootstrap'
});
tree.on('nodeDrop', function (e, MDA_ID, PARENT_MDA_ID) {
currentNode = MDA_ID ? tree.getDataById(MDA_ID) : {};
console.log("current Node = " + currentNode);
parentNode = PerentId ? tree.getDataById(PARENT_MDA_ID) : {};
console.log("parent Node = " + parentNode);
if (currentNode.PARENT_MDA_ID === null && parentNode.PARENT_MDA_ID === null) {
alert("Parent node is not droppable..!!");
return false;
}
// console.log(parent.HierarchyLevel);
var params = { MDA_ID: MDA_ID, PARENT_MDA_ID: PARENT_MDA_ID };
$.ajax({
type: "POST",
url: "/Mda/ChangeNodePosition",
data: params,
dataType: "json",
success: function (data) {
$.ajax({
type: "Get",
url: "/Mda/GetHierarchy",
dataType: "json",
success: function (records) {
Usertree.destroy();
Usertree = $('#Usertree').tree({
primaryKey: 'MDA_ID',
dataSource: records,
dragAndDrop: false,
checkboxes: true,
iconsLibrary: 'glyphicons',
//uiLibrary: 'bootstrap'
});
}
});
}
});
});
$('#btnGetValue').click(function (e) {
var result = Usertree.getCheckedNodes();
if (result == "") { alert("Please Select Node..!!") }
else {
alert("Selected Node id is= " + result.join());
}
});
//delete node
$('#btnDeleteNode').click(function (e) {
e.preventDefault();
var result = tree.getCheckedNodes();
if (result != "") {
$.ajax({
type: "POST",
url: "/Mda/DeleteNode",
data: { values: result.toString() },
dataType: "json",
success: function (data) {
alert("Deleted successfully ");
window.location.reload();
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
},
});
}
else {
alert("Please select Node to delete..!!");
}
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
// show model popup to add new node in Tree
$('#btnpopoverAddNode').click(function (e) {
e.preventDefault();
$("#modalAddNode").modal("show");
});
//Save data from PopUp
$(document).on("click", "#savenode", function (event) {
event.preventDefault();
$.validator.unobtrusive.parse($('#formaddNode'));
$('#formaddNode').validate();
if ($('#formaddNode').valid()) {
var formdata = $('#formaddNode').serialize();
// alert(formdata);
$.ajax({
type: "POST",
url: "/Mda/AddNewNode",
dataType: "json",
data: formdata,
success: function (response) {
// $("#modalAddNode").modal("hide");
window.location.reload();
},
error: function (response) {
alert('Exception found');
// $("#modalAddNode").modal("hide");
window.location.reload();
},
complete: function () {
// $('.ajax-loader').css("visibility", "hidden");
}
});
}
});
//Close PopUp
$(document).on("click", "#closePopup", function (e) {
e.preventDefault();
$("#modalAddNode").modal("hide");
});
$('.rbtnnodetype').click(function (e) {
if ($(this).val() == "Pn") {
$('.petenddiv').attr("class", "petenddiv hidden");
$("#ParentName").val("");
}
else {
$('.petenddiv').attr("class", "petenddiv");
}
});
});
</script>
}
As shown above, what I have created can only do one level node. I want want to create multi-level.Whereby, a child will be a parent to other children.
Please how do I achieve this.
You can see some ASP.NET examples about this at https://github.com/atatanasov/gijgo-asp-net-examples/tree/master/Gijgo.Asp.NET.Examples
Please use our examples in order to achieve that.
This My Parent View In this i am calling partialview(_CityList.cshtml).
#model MedicalOrbit.City
#{
ViewBag.Title = "CreateCity";
}
<h2>Add City</h2>
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
<div id="Maindiv" class="col-lg-7">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>City Details</h5>
<div class="ibox-tools">
<a class="collapse-link">
<i class="fa fa-chevron-up"></i>
</a>
</div>
</div>
<div class="ibox-content">
<div class="row">
<div class="col-sm-6 b-r">
#*<hr />*#
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
<div class="form-group">
<label>City Name:</label>
#*#Html.LabelFor(model => model.CityName, htmlAttributes: new { #class = "control-label col-md-2" })*#
<br>
<div >
#Html.EditorFor(model => model.CityName, new { htmlAttributes = new { #class = "form-control", placeholder = "Enter City" } })
#Html.ValidationMessageFor(model => model.CityName, "", new { #class = "text-danger" })
</div>
</div>
<br>
<div>
<input type="submit" value="Create" class="btn btn-w-m btn-primary" />
<input type="submit" value="Cancel" class="btn btn-w-m btn-success" />
</div>
</div>
<div>
<div id="CityList" class="col-sm-6">
#*#Html.Partial("_CityList");*#
#Html.Action("CityList", "City")
</div>
</div>
</div>
</div>
</div>
</div>
}
<div id="Editdiv">
#Html.Action("EditCity", "City")
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
Partial View(_CityList.cshtml)
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.CityName)
</th>
<th>Action</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.CityName)
</td>
<td>
#*#Html.ActionLink("Edit", "Edit", new { id = item.CityID })*#
#Ajax.ActionLink("Edit City", "EditCity", "City", new AjaxOptions()
{
UpdateTargetId = "Maindiv",
InsertionMode = InsertionMode.ReplaceWith
})|
#Html.ActionLink("Details", "Details", new { id = item.CityID }) |
#Html.ActionLink("Delete", "Delete", new { id = item.CityID }) |
#Html.ActionLink("Area", "Area", new { #class = "btn btn-warning btn-circle btn-lg fa fa-times", id = item.CityID })
</td>
</tr>
}
</table>
following is my Controller Code
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Validation;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MedicalOrbit.Controllers
{
public class CityController : Controller
{
MediOrbitDatabaseEntities db = new MediOrbitDatabaseEntities();
// GET: City
public ActionResult Index()
{
return View();
}
public ActionResult CityList()
{
return PartialView("_CityList", db.Cities.Where(x => x.status == false).ToList());
}
public ActionResult CreateCity()
{
return View();
}
// POST: City/CreateCity
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateCity(City city)
{
// TODO: Add insert logic here
if (ModelState.IsValid)
{
city.Users = "ashwini";
city.DateTime = DateTime.UtcNow;
city.status = false;
db.Cities.Add(city);
db.SaveChanges();
return RedirectToAction("CreateCity");
}
return View(city);
}
public ActionResult EditCity(int? id)
{
City city = db.Cities.Where(x => x.CityID == id).FirstOrDefault();
if (city == null)
{
return HttpNotFound();
}
return View(city);
}
// POST: /Admin/City/Edit
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult EditCity(City city)
{
if (ModelState.IsValid)
{
city.Users = "Ashwini";
city.DateTime = DateTime.UtcNow;
city.status = false;
db.Entry(city).State = EntityState.Modified;
db.SaveChanges();
RedirectToAction("CreateCity");
}
return PartialView("_EditCity",city);
}
}
}
Now what i want is in _CityList.cshtml partial view when user clicks the edit actionlink then main parent view should be replace with another partial view(_EditCity.cshmtl).how i can achieve this.i m not experience in mvc so plz help me.
I am showing you how to do partial views. Hopefully, you will have enough take away to utilize partial views within partial views, if you want.
There might be extra code to help you.
View:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>IndexValid4</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(function () {
$('#LOCATION_NUMBER').click(function () {
var store = $('#storeNbr').val();
this.href = this.href.split("?")[0];
this.href = this.href + '?LOCATION_NUMBER=' + encodeURIComponent(store);
});
})
</script>
</head>
<body>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">My Modal</h4>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<label class="btnIEFix">You can also, Click in Grey Area Outside Modal To Close</label>
<button title="You can also, Click in Grey Area Outside Modal To Close" type="button" class="btn btn-secondary bootBtnMargin" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
#Html.HiddenFor(r => r.storeNbr, new { id = "storeNbr" })
#*https://stackoverflow.com/questions/5838273/actionlink-routevalue-from-a-textbox*#
#Ajax.ActionLink(
"Trigger Ajax",
"ReleaseVersion",
null,
new AjaxOptions
{
UpdateTargetId = "result",
InsertionMode = InsertionMode.Replace,
HttpMethod = "GET"
},
new
{
id = "LOCATION_NUMBER"})
<div id="result"></div>
</body>
</html>
Controller:
public class HomeController : Controller
{
public PartialViewResult ReleaseVersion(string LOCATION_NUMBER = "")
{
return PartialView("_ReleaseVersion"); //, model
}
public ActionResult IndexValid4()
{
var storeViewModel = new StoreViewModel { storeNbr = 5 };
return View(storeViewModel);
}
_ReleaseVersion partial view in shared folder:
release version partial view
I keep getting a 404 and searching all over SO and cannot target the issue here. The form is the result of a render action and appears on the home page (home controller). However, I want it to post a different controller action and it keeps giving me a 404. I have included all the correct script for unobtrusive javascript as well as the necessary web.config settings and I'm unable to come across a similar problem from my research.
This is the partial with the form that is being rendered:
#model AFS.Models.SearchLocationModel
<div class="site-search-module">
<div class="site-search-module-inside">
#using (Ajax.BeginForm("SearchCare", "LevelOfCare", null, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, UpdateTargetId = "searchDiv" }, new { #class = "search-form", enctype = "multipart/form-data" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<div class="row">
<div class="col-md-12">
<h5>Select a category</h5>
#Html.DropDownListFor(x => x.Level, Model.LevelSelectList, new { #class = "form-control input-lg selectpicker" })
</div>
<div class="col-md-12">
<h5>Enter location</h5>
<input type="text" id="Location" name="Location" class="form-control input-lg selectpicker" placeholder="City, State OR Zip Code" required />
</div>
<div class="col-md-12"> <button type="submit" class="btn btn-primary btn-block btn-lg search"><i class="fa fa-search"></i> Search</button> </div>
</div>
}
</div>
The controller action is:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SearchCare(SearchLocationModel model)
{
if (ModelState.IsValid)
{
SearchLocationModel geocodeModel = Geocode(new SearchLocationModel() { Level = model.Level, Location = model.Location });
if (geocodeModel.Status == "OK")
{
Session["level"] = model.Level;
return RedirectToRoute("LevelCity", new { level = model.Level, state = geocodeModel.State, city = geocodeModel.City, latitude = geocodeModel.Latitude, longitude = geocodeModel.Longitude });
}
else
{
ModelState.AddModelError(string.Empty, "Please enter City, State OR Zip Code.");
return RedirectToAction("SearchWidget", "Home");
}
}
else
{
return RedirectToAction("SearchError");
}
}
I've been struggling for a while now with the Ajax.BeginForm.
So, what I want to achieve is:
Clicking a button that will open a Modal Popup with a Partial View inside.
When I close the Modal Popup by pressing the Save button the information will be reloaded on the target control id by call an action on the controller.
What is happening is that the first time I do this, everything seems to work as intended. However as soon as I try to add something else, it does not work anymore.
Here goes the code.
Heres the code on the view that is being loaded inside the Modal Popup
#model GEMS.Models.ViewModels.AddressVM
#{
string controllerName = ViewContext.RouteData.Values["controller"].ToString();
string actionName = ViewContext.RouteData.Values["action"].ToString();
}
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 class="modal-title" id="myModalLabel">#HTMLHelper.TranslateCRUDTitles(controllerName, actionName)</h4>
</div>
#using (Ajax.BeginForm(new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, OnSuccess = "ShowSuccess", OnFailure = "ShowFailure" }))
{
#Html.AntiForgeryToken()
<div class="modal-body">
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#foreach (System.Reflection.PropertyInfo prop in Model.GetDisplayProps())
{
switch (prop.Name)
{
case "NewAddressTypeName":
break;
case "AddressType":
<div class="form-group">
#Html.Label(prop.Name)
#Html.DropDownList("AddressTypeID", null, htmlAttributes: new { #class = "form-control" }).DisableIf(() => actionName == "Delete")
#Html.ValidationMessage(prop.Name, new { #class = "text-danger" })
</div>
break;
case "Country":
<div class="form-group">
#Html.Label(prop.Name)
#Html.DropDownList("CountryID", null, htmlAttributes: new { #class = "form-control" }).DisableIf(() => actionName == "Delete")
#Html.ValidationMessage(prop.Name, new { #class = "text-danger" })
</div>
break;
case "IsDefault":
<div class="form-group">
<label class="checkbox-inline">
#Html.Editor(prop.Name, new { htmlAttributes = new { #class = "grey" } }).DisableIf(() => actionName == "Delete")
#Html.Label(prop.Name)
</label>
#Html.ValidationMessage(prop.Name, new { #class = "text-danger" })
</div>
break;
case "SameAsID":
if (ViewBag.SameAsID != null)
{
<div class="form-group">
#Html.Label(prop.Name)
#Html.DropDownList(prop.Name, null, htmlAttributes: new { #class = "form-control" }).DisableIf(() => actionName == "Delete")
#Html.ValidationMessage(prop.Name, new { #class = "text-danger" })
</div>
}
break;
default:
<div class="form-group">
#Html.Label(prop.Name)
#Html.Editor(prop.Name, new { htmlAttributes = new { #class = "form-control" } }).DisableIf(() => actionName == "Delete")
#Html.ValidationMessage(prop.Name, new { #class = "text-danger" })
</div>
break;
}
}
#foreach (System.Reflection.PropertyInfo prop in Model.GetHiddenProps())
{
<input id="#prop.Name" name="#prop.Name" type="hidden" value="#Model.GetPropValue(prop.Name)">
}
</div>
<div class="modal-footer">
#if (actionName == "Delete")
{
<p>
#Resources.ConfirmAddressDelete
</p>
}
<button class="btn btn-yellow" type="button" data-dismiss="modal">
#Resources.Cancel <i class="fa fa-arrow-circle-left"></i>
</button>
#switch (actionName)
{
case "Create":
case "Edit":
<button class="btn btn-success" type="submit" value="Save">
#Resources.Save <i class="fa fa-save"></i>
</button>
break;
case "Delete":
<button class="btn btn-red" type="submit" value="Delete">
#Resources.Delete <i class="fa fa-times"></i>
</button>
break;
}
</div>
}
Here's the controller relevant actions:
public ActionResult Index(List<AddressVM> addressVMList)
{
addressVMList = addressVMList ?? (List<AddressVM>)TempData["AddressVMList"];
TempData["AddressVMList"] = addressVMList;
TempData.Keep("AddressVMList");
return PartialView("_Index", addressVMList);
}
public ActionResult Create()
{
TempData.Keep("AddressVMList");
ViewBag.AddressTypeID = new SelectList(AddressType.GetList(), "ID", "Name");
ViewBag.CountryID = new SelectList(Country.GetList(), "ID", "NiceName");
List<AddressVM> addressVMList = (List<AddressVM>)TempData["AddressVMList"];
return PartialView("_CreateEditDelete", new AddressVM());
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(AddressVM addressVM)
{
if (ModelState.IsValid)
{
//Create a fake ID in order to be able to edit and manipulate the address before it is actually saved
List<AddressVM> addressVMList = (List<AddressVM>)TempData["AddressVMList"];
addressVM.Id = (addressVMList.Count + 1) * -1;
addressVMList.Add(addressVM);
if (addressVM.IsDefault) ListedPropVM.SetDefault(addressVMList.Cast<ListedPropVM>().ToList(), addressVM.Id);
TempData.Keep("AddressVMList");
string url = Url.Action("Index", "Addresses", null);
return Json(new { success = true, url = url, method = "replaceTargetAddresses" });
}
// return PartialView("_CreateEditDelete", addressVM);
return RedirectToAction("Create");
}
And finally the script that is run when OnSuccess:
function ShowSuccess(data) {
if (data.success) {
$('#defaultModal').modal('hide');
$('#' + data.method).load(data.url);
}
}
function ShowFailure(data) {
alert('Problem occured');
}
Thanks in advance for your help and time.
Well I solved the problem by adding the following to the script on the partial view:
<script type="text/javascript">
**$(document).ready(function () {
$.ajaxSetup({ cache: false });
});**
function ShowSuccess(data) {
if (data.success) {
$('#defaultModal').modal('hide');
$('#' + data.method).load(data.url);
}
}
function ShowFailure(data) {
$('#defaultModalContent').html(result);
}
</script>
Hope this helps someone else.