View is not displaying after Post Request - asp.net-mvc

I'm making a post request from on view so that I don't see the parameters on the URL and I can tell it is passing the appropriate parameters to controller for the request but it does not display the appropriate view from that controller.
Calling view
#Ajax.ActionLink("Work1", "NewIndex", "WorkItems",
new
{
eventCommand = "createforrig",
//eventArgument1 = #item.Id,
eventArgument2 = #item.Id
},
new AjaxOptions
{
HttpMethod = "POST"
})
WorkItems Controller method
[HttpPost]
public ActionResult NewIndex(NewWorkItemViewModel vm)
{
vm.IsValid = ModelState.IsValid;
vm.HandleRequest();
if (vm.IsValid)
{
// NOTE: Must clear the model state in order to bind
// the #Html helpers to the new model values
ModelState.Clear();
}
else
{
foreach (KeyValuePair<string, string> item in vm.ValidationErrors)
{
ModelState.AddModelError(item.Key, item.Value);
}
}
return View(vm);
}
Putting a breakpoint on the last Return View(vm) confirms it is being called but the browsers does not update to display the workItems view.
Suggestions on why the browser is not being updated to display the appropriate view.

You're making an ajax post, the newly rendered view is being returned by the server if you were to look in the network console in your browser. Add a success callback. Either assign a callback to handle the response or use the
UpdateTargetId property in your AjaxOptions
#Ajax.ActionLink("Work1", "NewIndex", "WorkItems",
new
{
eventCommand = "createforrig",
//eventArgument1 = #item.Id,
eventArgument2 = #item.Id
},
new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "AjaxSuccess", //handle with callback
UpdateTargetId = "MyElementID" //update html element
})
if you choose to use OnSuccess then in javascript
function AjaxSuccess(data){
//handle response
}
AjaxOptions properties and usage can be found here
EDIT
You could use javascript to submit a form when a link is clicked, put a form somewhere in your code and hide it.
#using (Html.BeginForm("NewIndex", "WorkItems", FormMethod.Post,
new { class = "hidden", id = "postForm" } ))
{
<input type="hidden" name="eventCommand" value="createforrig" />
<input type="hidden" name="eventArgument2" value="#item.Id" />
<input type="submit" value="link text" id="submitForm"/>
}
then change your #Ajax.ActionLink... to
#Html.ActionLink("Work1", "NewIndex", "WorkItems", new { id = "postLink"})
and if you're using jQuery
<script>
$(function(){
$('#postLink').click(function(e)
{
e.preventDefault();
$('#postForm').submit();
});
});
</script>
and don't forget to hide the form in css
.hidden { display:none;}

Related

How can I pass a parameter together with the Model?

Here's my View (Model ActivityViewModel):
#model GPMS.Models.ActivityViewModel
<div class="tab-pane" id="managepayments" role="tabpanel">
#{ Html.RenderPartial("_Payments", Model.Payments); }
</div>
Which render a Partial (Model IEnumerable<GPMS.Models.PaymentViewModel>):
#model IEnumerable<GPMS.Models.PaymentViewModel>
#using (Ajax.BeginForm("SavePayments", "Activities", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "DynamicContainer", InsertionMode = InsertionMode.Replace, OnBegin = "AjaxBeginFormOnBegin", OnComplete = "AjaxBeginFormOnComplete", OnSuccess = "AjaxBeginFormOnSuccess", OnFailure = "AjaxBeginFormOnFailure" }))
{
#Html.AntiForgeryToken()
<!-- My Form -->
}
Which send Ajax request to my Controller's Action:
public ActionResult SavePayments(IEnumerable<PaymentViewModel> payments)
{
if (ModelState.IsValid) {
// code; here I need ActivityViewModel.ID
}
}
The question is: how can I pass to that SavePayments also my activity ID stored in ActivityViewModel.ID? Can I do with routing?
I don't want to pass the whole ActivityViewModel to SavePayments, otherwise I need to take care of its required fields for the ModelState.IsValid check.
One option is to use the overload of Html.Partial to pass the ID using additionalViewData, then retrieve it in the partial view and add it as a route value in the form.
In the main view
#{ Html.RenderPartial("_Payments", Model.Payments, new ViewDataDictionary { { "ID", Model.ID} }); }
And in the partial
#using (Ajax.BeginForm("SavePayments", "Activities", new { id = ViewData["ID"] }, new AjaxOptions { ....
Then add a parameter in the POST method for the ID
public ActionResult SavePayments(int id, IEnumerable<PaymentViewModel> payments)

How to pass an actionlink's results to a partialview placeholder?

Okay, so in my page I have a list of links:
#foreach (var item in Model)
{
#Html.ActionLink(item.Name, "Recruitments", new { Id = item.Id })
<br />
}
And what I want is for the partialview to return somewhere else on the page, in a placeholder I've set aside.
Is this possible? Or do I have to use jquery ajax calls instead somewhere?
you can #Ajax.ActionLink in asp.net mvc, it has different overloads you can use according to your requirements here is the code:
#Ajax.ActionLink("ActionName", // action name
"Recruitments", //controller name
new { Id = item.Id }, // route values
new AjaxOptions { HttpMethod = "GET", //HttpMethod Get or Post
InsertionMode = InsertionMode.Replace, // Replace content of container
UpdateTargetId = "Container", // id of element in which partial view will load
OnComplete = "Completed();" }) // js function to be executed when ajax call complete
<div id="Container">
</div>
<script>
function Completed()
{
alert("completed");
}
</script>
I did had a problem with partial for your problem post some code so I understand your problem.
Either you should use a razor helper, either you simply use jquery to manipulate the dom.
note that jquery is pretty simple
$("#selectorOnYourPlaceHolder").html($("#selectorOnYourLinks").html());
$("#selectorOnYourLinks").html("")
You want to do this with Ajax:
$.ajax({
type: "GET", url: "somePageOrHandler.aspx", data: "var1=4343&var2=hello",
success: function(data)
{
$('#someDivInPlaceHolder').html( data);
}
});

How to call script based on value of Model

I have the following code that is used when logging in and it works. However, if the login successful, I need to close the form. I have a button that does that which the user can click, but I don't know how to wire that up so I can call it programmatically. The Model has a property called IsAuthenticated. So if that is true, then I need to call the cancelLogin() function which will close the window.
#using (Ajax.BeginForm("Login", "Account", new AjaxOptions { InsertionMode = InsertionMode.Replace, UpdateTargetId = "loginSection", }))
{
#Html.Partial("_LoginInfoPartial", Model)
<input} type="submit" value="Log in" />
<button type="button" id="close_button" onclick="cancelLogin()" >Cancel</button>
<script>
function cancelLogin()
{
var window = $("#loginWindow").data("kendoWindow");
window.close();
}
</script>
}
From within your controller on a successful login, you could return a call to that function. For example:
public ActionResult Login() {
// login logic here
if(loginSuccess)
return Content("<script>cancelLogin();</script>");
else
return View();
}
So when the form loads from the backend, it will replace your div with this Javascript which should execute and close the window.

Invoking an action using jquery ajax

I am using ASP.NET MVC 2. I have a modal dialog (done through jquery UI) that contains two text boxes and a button. All the controls are inside a form.
I would like to invoke, when the user click the button, a controller action that do some operations on the passed data contained in the two text boxes and then return an integer value and a string message to the user.
Could anybody provide an example for doing this with jquery?
Thanks so much!
suppose you have the following form :
<form id="ajax-form">
<fieldset>
<input type="text" id="firstname" name="firstname" />
<input type="text" id="lastname" name="lastname" />
<input type="submit" value="send" />
</fieldset>
</form>
using jQuery
$(document).ready(function(){
$("#ajax-form").submit(function(){
$.ajax({
type: "POST",
url: "Person/Add",
data: $("#ajax-form").serialize(),
success: function (response) {
// whatever you want to happen on success
},
error: function (response) {
alert('There was an error.');
}
});
});
});
Accessing Your Data in the Action Method.
public ActionResult Add(FormCollection form)
{
string firstname = form["firstname"];
string firstname = form["lastname"];
// do whatever you want here
// then return something to the view
return Json(/*some object*/);
}
another way is to use Microsoft Ajax
<% using (Ajax.BeginForm("Add", "Person",
new AjaxOptions() {
UpdateTargetId = "formDiv",
InsertionMode = InsertionMode.Replace,
HttpMethod = "Post" })) {%>
<fieldset>
// Form Elements Here.
</fieldset>
<% } %>
UpdateTargetId is the id of the html element to be targeted.
The InsertionMode option has three values Replace, InsertAfter, InsertBefore
Hope that was helpful
Update : you don't have to return a Json result in your action method you can simply return a partial view or any HTML code as the response object and then insert it using jQuery.
You may take a look at the documentation about how you could implement a dialog that contains form fields. And when the confirm button is clicked you could simply send an AJAX request.
buttons: {
Confirm: function() {
// read the value in the textbox
var name = $('#name').val();
// send an AJAX request to an action that will return JSON:
$.getJSON('/home/foo', { name: name }, function(result) {
// read the returned value
alert(result.Value);
});
},
Cancel: function() {
$(this).dialog('close');
}
}
And your controller action:
public ActionResult Foo(string name)
{
return Json(new { Value = '123' }, JsonRequestBehavior.AllowGet);
}

Ajax Redirect to Page instead of Updating Target

I am using a partial view for login and would like to redirect the user to a new page on success and show the validation errors in the partial view if the model is invalid. The ajax target is being updated and success or failure. If the the model is valid, it is showing the entire new page in the update target but I want it to redirect to the new page. I have tried Redirect and RedirecttoAction but it is not getting the desire results. Any ideas on what I can to go get an ajax update to redirect to a new page, not update the target. Also, let me know if I am using the wrong approach.
Partial View Code:
<% using (Ajax.BeginForm(
"LogOn",
null,
new AjaxOptions {
HttpMethod = "POST",
UpdateTargetId = "SignInForm"
},
new {
id = "SignInForm", ReturnUrl = Request.QueryString["ReturnUrl"]
})) { %>
<<Page HTML Controls>>
<input type="submit" value="Log On" />
<% } %>
Here is the relevant controller code:
public ActionResult Logon(LogOnModel model,string returnUrl)
{
if (ModelState.IsValid)
{
//Login Logic Code
if (!String.IsNullOrEmpty(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "App");
}
}
// If we got this far, something failed, redisplay form
if (Request.IsAjaxRequest())
return PartialView("LogOnControl");
return View(model);
}
To perform a redirect you need to do it on the client side. So you can no longer use UpdateTargetId but you should instead use the OnSuccess option. You will also need to modify the Logon controller action so that in case of a redirect you test if you it is an ajax request and in this case return a Json object with the redirect url which will be used in javascript:
if (ModelState.IsValid)
{
if (string.IsNullOrEmpty(returnUrl))
{
returnUrl = Url.Action("Index", "App");
}
if (Request.IsAjaxRequest())
{
return Json(new { returnUrl = returnUrl });
}
return Redirect(returnUrl);
}
And in the view:
<% using (Ajax.BeginForm(
"LogOn",
null,
new AjaxOptions {
HttpMethod = "POST",
OnSuccess = "success"
},
new {
id = "SignInForm", ReturnUrl = Request.QueryString["ReturnUrl"]
})) { %>
<<Page HTML Controls>>
<input type="submit" value="Log On" />
<% } %>
<script type="text/javascript">
function success(context) {
var returnUrl = context.get_data().returnUrl;
if (returnUrl) {
window.location.href = returnUrl;
} else {
// TODO: update the target form element with the returned partial html
}
}
</script>

Resources