In Post Controller , URL is like this :
http://127.0.0.1/post/5006/some-text-for-seo-friendly
{contoller}/{id}/{seo}
public ViewResult Index(){
.....
}
I used Ajax.BeginForm in index view and mapped it to AddComment action in the same controller.
#using (Ajax.BeginForm("AddComment", "Post", new AjaxOptions()
{
HttpMethod = "GET",
InsertionMode = InsertionMode.InsertAfter,
UpdateTargetId = "comment-container"
}))
{
<textarea cols="2" rows="2" name="comment" id="comment"></textarea>
<input type="submit" value="Add Comment" />
}
and in controller
public PartialViewResult AddComment(string comment){
// how can I get 5006 {id} here
}
my question is how can I get the {id} [5006] in AddComment action.
note : the hard way is using Request.UrlReferrer and split by '/' and select form array .
You need to supply the id to the BeginForm method using this overload which takes a routeValues parameter:
#using ( Ajax.BeginForm( "AddComment", "Post",
new { id = 5006 },
new AjaxOptions
{
...
Then you should just be able to take the id as a parameter of your action method:
public PartialViewResult AddComment( int id, string comment )
{
...
MVC will call AddComment with the populated id value.
Related
I have an Ajax form with 3 buttons for submission/cancel. The Post goes through fine and when it redirects to the next page it should go to, the correct action is called, but that new Action detects it as an Ajax request and instead of returning the full page, it tries returning a partial.
View contains:
#using (Ajax.BeginForm("postingAction", "Controller", new AjaxOptions { HttpMethod = "post" }, new { id = "myId" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<buttons>
...
<input type="submit" name="Cancel" value="Cancel" class="btn btn-default" />
</buttons>
...
}
Action that is called for the post:
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "userType1, userType2")]
public ActionResult postingAction(myViewModel model)
{
if (Request.Form["Cancel"] != null)
return RedirectToAction("Action2", "DiffController");
...
}
Now when this RedirectToAction happens, this second action still detects that it was an Ajax call, how do I remove that it was an ajax call and make it a normal call?
Thanks,
David K.
Try returing JavaScriptResultwith desired url.
[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = "userType1, userType2")]
public ActionResult postingAction(myViewModel model)
{
if (Request.Form["Cancel"] != null)
return JavaScript( "window.location = '" + Url.Action("Action2","DiffController") + "'" )
...
}
http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.javascript%28v=vs.118%29.aspx
I am building a page where a user can view the details of an item which s/he selected.
As part of this project, I need to show all the comments that are listed under this particular item using Ajax and partial views.
In the Controller class, I am somehow unable to pass the productID of the selected item to the partial view method. When I hard code the productID into the method, the comments show up, however when I pass it through the parameter, the method won't even trigger.
All the product details, however, show without restrictions.
I would appreciate any help. Below please find the code in my Controller
public ActionResult Index()
{
List<Product> productList = new ProductClient().GetAllProducts().ToList();
return View("Index", productList);
}
//This method works correctly. The id of the product is passed.
public ActionResult Details(int id)
{
return View(new ProductClient().GetProductByID(id));
}
// This method is not even getting triggered.
public PartialViewResult ProductComments(int id)
{
List<Comment> commentList = new ProductCommentClient().GetCommentsByProductID(id).ToList();
return PartialView("_comments", commentList);
}
This is my Details.cshtml
#Ajax.ActionLink("Product Comments", "ProductComments(" + #Model.ID + ")", new AjaxOptions
{
HttpMethod = "Get",
UpdateTargetId= "divComments",
InsertionMode = InsertionMode.InsertAfter
})
<fieldset>
<div id="divComments">
<legend>Comments</legend>
</div>
</fieldset>
Many thanks in advance.
I solved this.
#Ajax.ActionLink("Product Comments", "ProductComments", new {id=Model.ID}, new AjaxOptions
{
HttpMethod = "Get",
UpdateTargetId= "divComments",
InsertionMode = InsertionMode.InsertAfter
})
<fieldset>
<div id="divComments">
<legend>Comments</legend>
</div>
</fieldset>
I was passing the ID in the wrong manner. I hope that this would at least help somebody else.
I have a ViewModel which contains a List of my Model, like so:
public class OrderConfirm
{
public ICollection<DayBookQuoteLines> SalesLines { get; set; }
public ICollection<DayBookQuoteLines> LostLines { get; set; }
public string Currency { get; set; }
}
I then use this ViewModel in my View like so:
#model btn_intranet.Areas.DayBook.Models.ViewModels.OrderConfirm
#{
ViewBag.Title = "Daybook - Order Confirmation";
}
<h6>Sales Lines</h6>
<div id="SalesOrders">
#using (Ajax.BeginForm("ConfirmSalesOrder", new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "SalesOrders",
OnBegin = "SalesOrderConfirm"
}))
{
#foreach(var item in Model.SalesLines)
{
<p>#item.ItemName</p>
<p>#item.Qty</p>
#* Other Properties *#
}
<input type="submit" value="Submit Sales Order" />
}
</div>
<h6>Lost Lines</h6>
<div id="LostOrders">
#using (Ajax.BeginForm("ConfirmLostOrder", new AjaxOptions()
{
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "LostOrders",
OnBegin = "LostOrderConfirm"
}))
{
#foreach(var item in Model.SalesLines)
{
<p>#item.ItemName</p>
<p>#item.Qty</p>
#* Other Properties *#
}
<input type="submit" value="Submit Lost Order" />
}
</div>
The problem is, in my [HttpPost] actions, both ConfirmSalesOrder and ConfirmLostOrder. The value of my Model passed as a parameter is null:
[HttpPost]
public ActionResult ConfirmSalesOrder(List<DayBookQuoteLines> quoteLines)
{
// Process order...
return PartialView("Sales/_ConfirmSalesOrder");
}
so quoteLines is null. How can I bind the form to my model?
You don't have any input field in your form that will send the values to the server. You are only displaying them. That's why they are null when you submit the form => nothing is sent to the server.
But if inside this form the user is not supposed to modify any of the values all you need to do is to pass an id to the controller action that will allow you to fetch the model from the exact same location from which you fetched it in your GET action that rendered this form.
In this case your action will look like this:
[HttpPost]
public ActionResult ConfirmSalesOrder(int id)
{
List<DayBookQuoteLines> quoteLines = ... fetch them the same way as in your GET action
// Process order...
return PartialView("Sales/_ConfirmSalesOrder");
}
If on the other hand the user is supposed to modify the values in the form you need to provide him with the necessary input fields: things like textboxes, checkboxes, radio buttons, dropdownlists, textereas, ... And in order to generate proper names for those input fields I would recommend you using editor templates instead of writing foreach loops in your views.
UPDATE:
Seems like the user is not supposed to edit the data so there are no corresponding input fields. In this case in order to preserve the model you could during the AJAX request you could replace the Ajax.BeginForm with a normal Html.BeginForm an then manually wire up the AJAX request with jQuery. The advantage of this approach is that now you have far more control and you could for example send the entire model as a JSON request. To do this you could store the model as a javascript encoded variable inside the view:
<script type="text/javascript">
var model = #Html.Raw(Json.Encode(Model));
</script>
and then AJAXify the form:
$('#formId').submit(function() {
$.ajax({
url: this.action,
type: this.method,
contentType: 'application/json',
data: JSON.stringify({ quoteLines: model }),
success: function(result) {
$('#someTargetIdToUpdate').html(result);
}
});
return false;
});
I am tring to pass a RouteValueDictionary to my aspx so that I can use it as the parameters for an Ajax.BeginForm method. I load it up like so:
RouteValues = new System.Web.Routing.RouteValueDictionary();
RouteValues.Add("FindingId", thisFinding.Id);
RouteValues.Add("ReportId", thisFinding.ReportSection.ReportId);
and then add it to my model without issue. When I put it as the parameter to the BeginForm method it renders the action as this:
/SolidWaste/Finding/LoadSection?Count=3&Keys=System.Collections.Generic.Dictionary%602%2BKeyCollection%5BSystem.String%2CSystem.Object%5D&Values=System.Collections.Generic.Dictionary%602%2BValueCollection%5BSystem.String%2CSystem.Object%5D
Here is the aspx code:
(Ajax.BeginForm(Model.FormModel.Action,
Model.FormModel.Controller,
Model.FormModel.RouteValues,
new AjaxOptions {
HttpMethod = "Post",
InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace,
UpdateTargetId = "WindowContent",
}, new { id = FormId })) { %>
<input name="submit" type="submit" class="button" value="" style="float: right;"/>
<% } //End Form %>
Here is the View Model that represents Model.FormModel
public class FormViewModel {
public string Action { get; set; }
public string Controller { get; set; }
public string Method { get; set; }
public RouteValueDictionary RouteValues { get; set; }
}
Any idea why it is not serializing the RouteValueDictionary into the proper URL on the action? I would like to use an object here rather than build the RouteValues by hand with new { field = vale }
Ah, you are using the wrong overload. It's normal. The ASP.NET MVC team really made a mess out of this API. You gotta be careful which method you are invoking. Here's the overload that you need:
<% using (Ajax.BeginForm(
Model.FormModel.Action, // actionName
Model.FormModel.Controller, // controllerName
Model.FormModel.RouteValues, // routeValues
new AjaxOptions { // ajaxOptions
HttpMethod = "Post",
InsertionMode = System.Web.Mvc.Ajax.InsertionMode.Replace,
UpdateTargetId = "WindowContent",
},
new Dictionary<string, object> { { "id", FormId } }) // htmlAttributes
) { %>
<input name="submit" type="submit" class="button" value="" style="float: right;"/>
<% } %>
Notice the correct overload? You were using the one that was taking routeValues and htmlAttributes as anonymous objects, except that you was passing Model.FormModel.RouteValues as a RouteValueDictionary which basically crapped your overload.
Hit F12 while hovering the cursor over the BeginForm and if you are lucky enough and Intellisense works fine for you in Razor views (which rarely happens) you will get redirected to the method you are actually invoking and realize your mistake.
in my view:
<script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="../../Scripts/MicrosoftMvcAjax.debug.js" type="text/javascript"></script>
<script src="../../jquery-1.4.1-min.js" type="text/javascript"></script>
<%= Ajax.ActionLink("Update", "Index", "Home", new AjaxOptions { UpdateTargetId = "time" })%>
<br />
<div id="time">
<% Html.RenderPartial("TimeControl"); %>
</div>
in my controller:
[HttpGet]
public ActionResult Index()
{
HomeModel model = new HomeModel(Request.Url.Host);
// Normal Request
if (!Request.IsAjaxRequest())
{
return View("Index", model);
}
// Ajax Request
return PartialView("TimeControl");
}
in my model:
public HomeModel()
{
Time = DateTime.Now;
}
i think everything is ok, but if iam clicking update link, time will be not updated.. why?
it schould be actual if i click update link
I suggest you do the following:
[HttpGet]
public ActionResult Index()
{
HomeModel model = new HomeModel(Request.Url.Host);
return View("Index", model);
}
[HttpPost]
public ActionResult Index()
{
HomeModel model = new HomeModel(Request.Url.Host);
// Ajax Request
return PartialView("TimeControl");
}
I think the problem might be that the AJAX request is a POST.
You may simply try to (1) remove [HttpGet] or (2) set the HttpMethod in the AjaxOptions to "GET".
Ajax.ActionLink("Update", "Index", "Home", new AjaxOptions { UpdateTargetId = "time", HttpMethod = "get" })
That should solve the problem.
(3) If it doesn't, check if you are using the correct overload. This should work:
Ajax.ActionLink("Update", "Index", "Home", null, new AjaxOptions { UpdateTargetId = "time" }), null)
Any of the options in my previous answers could solve your problem if the AJAX isn't working correctly with your application.
Buy in your example, you're also using something that wasn't quite clear to me.
You use a constructor overload that takes the url. And you use the default constructor to set the time. Is the constructor you use (the one that takes the url) also calling the parameterless constructor?
That constructor should do something like this:
public HomeModel(paramter.......) : this()
{
// Whatever...
}