ASP.NET MVC form on a Partial View - asp.net-mvc

I have page witha table and a button. When I push the button a partial view loads into a div. On the partial view there is an ajax form which sends back the partial view with validation error in case of wrong form data but I want to remove the partial view and refresh the table in case of successful insertion.
The form header:
#using (Ajax.BeginForm("RequestInsert", "Home", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "requestForm" }, new { id = "reqins" }))
The jQuery submit event handler on the host page:
$(document).on('submit', '#reqins', function (e) {
e.preventDefault();
let data = $("form :input").serializeArray();
$.ajax({
url: '#Url.Action("RequestInsert", "Home")'
,type: "POST"
,data: { "__RequestVerificationToken": token, "model": data }
})
.done(function (data) {
$("#requestForm").html("");
table.search('').columns().search('').draw();
})
.fail(function (jqXHR, textStatus) {
alert("fail");
});
});
I am a little confused with the partial view and ajax form.

Since your objective is checking validation status from AJAX response, you can use if condition against AJAX response as shown below:
$('#reqins').submit(function (e) {
e.preventDefault();
let data = $('form :input').serializeArray();
$.ajax({
url: '#Url.Action("RequestInsert", "Home")',
type: 'POST',
data: { "__RequestVerificationToken": token, "model": data },
success: function (result) {
// check valid response
if (result.invalid) {
$('#requestForm').html(result.form);
}
else {
$('#requestForm').html(result);
table.search('').columns().search('').draw();
}
},
error: function (jqXHR, textStatus) {
alert("fail");
}
});
});
Then inside controller action you can return both validation status and partial view using Controller.Json() with RenderViewToString() extension method provided here:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RequestInsert(ViewModel model)
{
// perform validation here
// assume IsValid is a boolean returned from validation status
if (IsValid)
{
// successful validation, return empty form
return PartialView("FormPartialView");
}
else
{
// validation failed, return failure status and previously-filled form
return Json(new { invalid = true, form = RenderViewToString(PartialView("FormPartialView", model)) });
}
}

try this and remove the Ajax Helper
$('#reqins').on('click', function () {
let data = $("form :input").serializeArray();
$.ajax({
url: '#Url.Action("RequestInsert", "Home")'
,type: "POST"
,data: data
,success:function (result) {
$("#requestForm").html(result);
}});
});
modify your action to this
public JsonResult RequestInsert()
{
try
{
return Json(new { success = true, result = PartialView("Prtialview") });
}
catch (Exception ex)
{
return Json(new { success = false, result = ex.ErrorMessage });
}
}
and then modify the client side as following
$('#reqins').on('click', function () {
let data = $("form :input").serializeArray();
$.ajax({
url: '#Url.Action("RequestInsert", "Home")'
,type: "POST"
,data: data
,success:function (result) {
if(result.succuss)
{
$("#requestForm").html(result);
}
else
{
alert("Error");
}
}});
});

Related

My partial view does not refresh after AJAX call

I am having an issue not able to refresh my Partial view.
my cshtml page page
<script type="text/javascript">
$(document).ready(function () {
$('#btncreate').click(function () {
var projectid = $("#txtprojectid").val();
$.ajax({
url: '/Projects/CreateFinanceItems?pid=' + Id,
datatype: 'json',
type: "POST",
success: function (response) {
alert("record created successfully");
if (response != null) {
window.close();
refreshpartial();
}
}
})
});
function refreshpartial()
{
$.ajax({
url: '/Projects/PartialItem?id=' + "Test",
datatype: 'json',
success: function (response) {
$("#displayproContainer").html(response);
},
error: function (xhr, ajaxOptions, thrownError) {
}
})
}
});
</script>
I can see record created successfully alert message, but when it goes to refreshpartial method my partialview does not refresh with Added data. I put the alert in success function it does not hit.
Partialview DIV ID #displayproContainer
$("#displayproContainer").html(response);
Controller code
[OutputCache(Duration = 0)]
public PartialViewResult PartialItem(string id)
{
// Logic to Insert data
return PartialView(viewModel);
}
Something I am missing here?

How to send json object to the Controller Action method in MVC 4

I am trying to send my userid and password to my login Controller Action method.
//Login button click code
$("#btnLogin").click(function () {
var userCrdential = {
UserName: $("inputEmail3").val(),
Password: $("inputPassword3").val()
};
$.ajax({
type: "POST",
url: "/Home/Login",
content: "application/json; charset=utf-8",
dataType: "json",
data: userCrdential,
success: function (res) {
// alert("data is posted successfully");
if (res.success == true)
alert("data is posted successfully");
else {
// alert("Something went wrong. Please retry!");
}
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr.statusMessage);
}
});
});
and in my home Controller I have login Action method
[HttpPost]
[ActionName("Login")]
public ActionResult Login(User userCrdential)
{
string userIdtest = userCrdential.UserName;
string userPasswordtest = userCrdential.Password;
var result=false;
if (userIdtest != null && userPasswordtest != null)
{
result = true;
}
else
{
result = false;
}
return Json(result);
//return RedirectToAction("Index");
}
but my action method is not invoking...
You need to change content to contentType and call JSON.stringify on your data:
$.ajax({
type: "POST",
url: "/Home/Login",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(userCrdential),
...
});
See jQuery.ajax
Just change it from:
var userCrdential = {
UserName: $("inputEmail3").val(),
Password: $("inputPassword3").val()
};
to:
var userCrdential = "UserName=" + $("inputEmail3").val() + "&Password=" + $("inputPassword3").val();
all other things is ok in your code, but make sure your controller parameter having the same parameters passing here i.e. UserName and Password.
however you need to check user input before calling ajax.
You should never hard-code URLs in MVC.
Instead use #Url.Action.
url: ('#Url.Action("Login", "Home")',
userCrdential needs to be JSON encoded:
JSON.stringify(userCrdential)
Also, for the same of your sanity, please use the fail method.
$.ajax("url")
.done(function() {
alert("success");
})
.fail(function() {
alert("error");
})
One last note, success is deprecated as of jQuery 1.8; you should use done instead.

How to bind IDictionary data in a Webgrid

i have a ajax call which calls the ControllerName "Floor" and ActionMethod "GetHotelingList".i have a Dropdown list facility. when i select option from the Dropdownlist list the control goes to ajax call.based on selection value, the Webgrid must be displayed. #grdHoteling is Webgrid id.
$.ajax({
type: 'GET',
url: '/Floor/GetHotelingList',
cache: false,
contentType: 'application/html; charset=utf-8',
dataType: 'html',
data: { floorId: floorId },
success: function (data) {
debugger;
$("#grdHoteling").val(data);
//debugger;
//$("#grdHoteling").html(data);
},
complete: function () {
},
error: function () {
if (facilityName.indexOf('-') != -1) {
$('#floor').empty();
return;
}
else
alert("Error in generating hoteling information");
}
});
Here is the ActionMethod GetHotelingList value is paased floorId for some fileration.
public List<IDictionary> GetHotelingList(int floorId)
{
var model = new List<IDictionary>();
using (var context = new FloorContext())
{
try
{
model = ListHotelingByFloorId(context, floorId);
}
catch (Exception ex)
{
}
}
return model;}
On Success of the ajax call, when i check through debugger am getting data as "System.Collections.Generic.List`1[System.Collections.IDictionary]" and child cannot be evaluated.
kindly help...!
thanks...!

MVC: used partial view for jquery modal popup, issues with validation

So i have a button in a view that opens up a modal pop up form. This modal pop up form is a partial page. My issue with this is that:
Whenever I don't fill up the required fields on the form, the TryUpdate check will obviously fail, but it will just refresh the whole page cuz of the line "window.location.reload" on the jquery. What I wanted to do is that instead of refreshing, it would still stay as it is (the page with the modal showing) and validation summary or validations will show up saying, this and that are required. Is this possible or am I complicating stuff with it?
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('#modal-link').click(function () {
var href = this.href;
$('#load-modal').dialog({
modal: true,
draggable: false,
position: "top",
open: function (event, ui) {
$(this).load(href, function (result) {
$('#new-academy-form').submit(function () {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (json) {
window.location.reload(true);
},
error: function (data) {
var errmessage = '<div class="error-repo">Error</div>';
$('#messages').html(errmessage);
}
});
return false;
});
});
}
});
return false;
});
});
});
</script>
This is the button:
<div class="width3">
<%: Html.ActionLink("Submit New", "Create", "Propose", null, new { #class = "results", id = "modal-link" })%>
</div>
This is the action:
public ActionResult Create()
{
return PartialView(Propose.LoadDetails(context, null));
}
[HttpPost]
public ActionResult Create(FormCollection formCollection)
{
Propose propose= new Propose ();
if(TryUpdateModel(propose, "Propose ")){
context.Propoe.Add(propose);
context.SaveChanges();
var proposals = new System.Text.StringBuilder();
return Json(new { propose= proposals});
}
return PartialView(Propose.LoadDetails(context, null));
}
You can return a flag from your action.
var data = new {isSuccess, new { propose= proposals}};
return Json(data , JsonRequestBehavior.AllowGet);
and then use it in jquery like
success: function (data) {
if(data.isSuccess){
window.location.reload(true);
}
else{
// write code to show validation summary and no reload.
}
}

How can I RedirectToAction within $.ajax callback?

I use $.ajax() to poll an action method every 5 seconds as follows:
$.ajax({
type: 'GET', url: '/MyController/IsReady/1',
dataType: 'json', success: function (xhr_data) {
if (xhr_data.active == 'pending') {
setTimeout(function () { ajaxRequest(); }, 5000);
}
}
});
and the ActionResult action:
public ActionResult IsReady(int id)
{
if(true)
{
return RedirectToAction("AnotherAction");
}
return Json("pending");
}
I had to change the action return type to ActionResult in order to use RedirectToAction (originally it was JsonResult and I was returning Json(new { active = 'active' };), but it looks to have trouble redirecting and rendering the new View from within the $.ajax() success callback. I need to redirect to "AnotherAction" from within this polling ajax postback. Firebug's response is the View from "AnotherAction", but it's not rendering.
You need to consume the result of your ajax request and use that to run javascript to manually update window.location yourself. For example, something like:
// Your ajax callback:
function(result) {
if (result.redirectUrl != null) {
window.location = result.redirectUrl;
}
}
Where "result" is the argument passed to you by jQuery's ajax method after completion of the ajax request. (And to generate the URL itself, use UrlHelper.GenerateUrl, which is an MVC helper that creates URLs based off of actions/controllers/etc.)
I know this is a super old article but after scouring the web this was still the top answer on Google, and I ended up using a different solution. If you want to use a pure RedirectToAction this works as well. The RedirectToAction response contains the complete markup for the view.
C#:
return RedirectToAction("Action", "Controller", new { myRouteValue = foo});
JS:
$.ajax({
type: "POST",
url: "./PostController/PostAction",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function (result) {
if (result.responseText) {
$('body').html(result.responseText);
}
}
});
C# worked well
I just changed the JS because responseText was not working for me:
$.ajax({
type: "POST",
url: posturl,
contentType: false,
processData: false,
async: false,
data: requestjson,
success: function(result) {
if (result) {
$('body').html(result);
}
},
error: function (xhr, status, p3, p4){
var err = "Error " + " " + status + " " + p3 + " " + p4;
if (xhr.responseText && xhr.responseText[0] == "{")
err = JSON.parse(xhr.responseText).Message;
console.log(err);
}
});
You could use the Html.RenderAction helper in a View:
public ActionResult IsReady(int id)
{
if(true)
{
ViewBag.Action = "AnotherAction";
return PartialView("_AjaxRedirect");
}
return Json("pending");
}
And in the "_AjaxRedirect" partial view:
#{
string action = ViewBag.ActionName;
Html.RenderAction(action);
}
Reference:
https://stackoverflow.com/a/49137153/150342

Resources