How to get my Action method to give me back my model from web grid with checkboxes - asp.net-mvc-3

I have a strongly typed view which is uses an IEnumerable as its model.
There's a bool property on the model which I'm rendering in a MVC WebGrid in a checkbox which the user can then check or uncheck.
On submit it gets to my action method but how do I get the checked checkboxes?
If I look at the Request.Params, I see all the checked checkboxes coming back as parameters. Is there any easy way for the DefaultModelBinder to convert these back into my IEnumerable, or do I have to do this by hand?
Here's my View so far:
#model IEnumerable<XXX.XXXItemDto>
<div id="items">
#using (Ajax.BeginForm("SaveEvents", "MyController", new AjaxOptions { UpdateTargetId = "items" }))
{
var grid = new WebGrid(Model, canPage: false, canSort: false);
#grid.GetHtml(columns: grid.Columns(
grid.Column("itemDescription", header: "Event"),
grid.Column("acknowledged", format: #<text><input name="Acknowledged_#(item.staffItemOid)" type="checkbox" value="#item.staffItemOid" #(item.acknowledged ? "Checked" : null)/> </text>, header: "Acknowledged")
))
#Html.SubmitButton("Save")
}
</div>

Related

MVC5 Ajax.ActionLink in new Page [duplicate]

I'm trying to get a partial view to load on my current view when the user clicks the link but it keeps loading the partial view rather then on the same view.
Not sure what I'm missing.
Main View Controller
public PartialViewResult MonitorDetail(MonitorType mType)
{
return PartialView("MonitorDetail", mType);
}
Main View
<script src="~/Scripts/jquery-2.1.1.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
<p class="lbutton radius">
#Ajax.ActionLink("SQL Cluster Online ", "MonitorDetail", "NOCCon", MonitorType.AHSSQLCluster, new AjaxOptions() { UpdateTargetId = "monitorDetail" })
<span class="lbutton-addition #(Model.SQLClusterOnline ? "online" : "offline")">
#(Model.SQLClusterOnline ? "Online" : "Offline")
</span></p>
<div id="monitorDetail"></div>
Partial View
#model PAL.Intranet.MonitorType
<div>
You choose #Model.ToString()
</div>
Also keeps telling me mType is null but i'm passing it MonitorType in the ActionLink so I added it as nullable so I can try and figure out the first issue and then work on the second.
If its displaying only the partial view, its because you have not included the required files for Ajax.ActionLink to work (and its just performing a normal redirect). Ensure you have included jquery.{version}.js and jquery.unobtrusive-ajax.js
The reason parameter mType is null is because you are not passing a value. It should be
#Ajax.ActionLink("SQL Cluster Online ", "MonitorDetail", "NOCCon", new { mtype = MonitorType.AHSSQLCluster }, new AjaxOptions() ....)

mvc3 partialview target by div tag

I have an issue with a partialview, for some reason when I do a Post on it; it gives me another copy of my form; how can I make that behavior go away . This is what that partialview looks like:
// this is all inside my partialview
<div style=" float:left;">
#using (Ajax.BeginForm("posting", "post", null, new AjaxOptions
{
UpdateTargetId = "glober",
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST"
}))
{
// taken out
}
</div>
<div id="glober">
#foreach (var item in Model.Mymodel)
{
}
</div>
as you can see this is a POST and I only want to update the part with the id of "glober" which it does but for some reason when I do the post it also gives me a second copy of the form elements. If inside my ajax form I have 1 textbox called firstname then after submitting it I get 2 textboxes that says firstname, any help would be great.
Part of my controller is this were i call out the partial
var iefeeds = sqlConnection.Query<thread>("Select * from postings").ToList();
return PartialView("_mypartial");
I think you have returned View rather than PartialView in the controller. So you'll see 2 pages overlapping in response of ajax Post.

Update partial view after edit

I have the following index:
<div id='addProduct'>
#{ Html.RenderPartial("Create", new BoringStore.Models.Product()); }
</div>
<div id='productList'>
#{ Html.RenderPartial("ProductListControl", Model.Products); }
</div>
The partial Create view contains an invisible div which is used to create a new product.
After doing so the partial view ProductListControl is updated.
Now I want to do so with an edit function.
Problem: It's not possible to integrate the edit page while loading the index because at this moment I don't know which product the user wants to edit.
My thought:
I'd like to call my existing edit view in an jquery modal (not the problem) so the user can perform changes.
After saving the modal is closed (still not the problem- I could handle this) and the ProductListControl is updated (here's my problem ... :().
How am I able to do so?
I've seen some tutorials but I'd like to keep it as clean & easy as possible.
Most of them are using dom manipulating and get feedback from the server (controller) by a JsonResult.
If possible I'd like to stick to the razor syntax, no pure JavaScript or jquery and if possible I'd like to avoid JsonResults.
One way might be to use the Ajax.BeginForm for your create product view.
The Ajax.BeginForm accepts a number of AjaxOptions, one being the UpdateTargetId (your DOM id, in this case your productlist div), more info here.
Then in your product controller code you can return a partial view, with the product list. So for example:
Index.cshtml
#using (Ajax.BeginForm("AjaxSave", "Product", new AjaxOptions { HttpMethod = "GET", UpdateTargetId = "productList", InsertionMode = InsertionMode.Replace }))
{
// your form
<p>
<input type="submit" value="Save" />
</p>
}
...
<div id="productList">...
</div>
ProductController.cs
[HttpGet]
public ActionResult AjaxSave(Product product)
{
if (ModelState.IsValid)
{
// save products etc..
}
var allProducts = _productService.GetAllProducts();
return PartialView("ProductListControl", allProducts);
}
There is a nice article on about this here.

Validate only ajax loaded partial view

I have a form with some controls. There is a button on the form which loads a partial view. Inside the partial view, there are two required field textboxes along with a button. And when its clicked, I need to display error messages only for textboxes which are inside the partial view, but not for the fields in the actual form. And when I click form's submit button, all error messages must show up.
After partial view is loaded, I am re-initializing the validation plugin as below.
$('#test').removeData("validator");
$.validator.unobtrusive.parse('#test');
I tried using validation attribute described in below thread but its not working. Maybe it works for normally loaded views.
ASP.NET MVC Validation Groups?
However, I can validate individually by calling textbox1.valid() and textbox2.valid(). But I think I am missing standard way of doing it. Any help is appreciated.
you can do this by submitting your partial view using Ajax.BeginForm()
//In Partail View
#model SomeModel
#using (Ajax.BeginForm("SomeActionName", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "targetId"}))
{
#Html.EditorFor(mode=>model.FirstText)
#Html.EditorFor(mode=>model.SecText)
<input type="submit" value="save">
}
//In Controller
public ActionResult SomeAction(SomeModel model)
{
return PartaiulView(model);
}
here you can validate your Partial View
NOTE: when you submit you form using Ajax.BeginForm you must specify "UpdateTargetId" where your result will be appear on View.
//In View
<div id="targetId">
#Html.Partail("PartialView")
</div>
OR if you want to Redirect to another action if your model is valid then modified your action
public ActionResult SomeAction(SomeModel model)
{
if(ModelState.IsValid)
{
return Json(new {redirect = #Url.Action("SomeAction","SomeController")})
}
return PartaiulView(model);
}
then in partail view you can invoke OnSuccess method of Ajax.BeginForm
#using (Ajax.BeginForm("SomeActionName", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "targetId",OnSuccess="success"}))
{
}
<script type="text/javascript">
function success(data)
{
if(data.redirect)
{
windows.location = data;
}
}
</script>
check both way which one is suitable to you.

Post form data to Controller's action with Ajax

I have a page in MVC3, with a link (Ajax.ActionLink). When user clicks it, it calls controller's action, and the result is inserted into a div, with replace.
Code is shown below:
#Ajax.ImageActionLink("/Images/btn_share.png", "Share pool", "SharePool", new { poolKey = Model.Id, poolName = Model.Name },
new AjaxOptions {
UpdateTargetId="popup",
HttpMethod="GET",
InsertionMode = InsertionMode.Replace,
LoadingElementId="loading_dialog",
OnSuccess = "ShowPopup('#popup_share', true, true)"
}
ImageLinkAction is custom extension method to use image as link, and ShowPopup is a javascript function that shows the updated div (to make it look as a popup)
Now the markup code inserted into the div which creates the popup contains a form as below
<div>
#using (Html.BeginForm()) {
#Html.HiddenFor(model => model.ID)
<div class="editor-label">
#Html.LabelFor(model => model.EmailAddress)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.EmailAddress)
#Html.ValidationMessageFor(model => model.EmailAddress)
</div>
// ... other fields
#Html.ValidationSummary(true)
<p>
<button type ="submit">Share</button>
</p>
}
</div>
The issue is with the form's submit: the Submit button calls the proper action but with a postback, which cause my page to refresh. What I need is to post data with ajax, receive the response, which is another partial view that gets inserted into the
I was trying to replace the Submit button with Ajax.ActionLink as below
#Ajax.ActionLink("Share", "Share",
new Models.MyModel
{
ID = Model.ID,
EmailAddress = Model.EmailAddress
},
new AjaxOptions
{
UpdateTargetId="popup",
HttpMethod="POST",
InsertionMode = InsertionMode.Replace,
LoadingElementId="loading_dialog",
OnSuccess = "ShowPopup('#popup_share', true, true)"
}
The controller's code looks like this:
[HttpPost]
public ActionResult SharePool(MyModel model)
{
// ...
return PartialView("_MyPartialView", model)
}
The problem is, in the moment the Ajax ActionLink is rendered (when form is loaded) there is no value in Model.EmailAddress, so my POST action in controller receives only ID parameter.
How can I handle this? Ideally, I think I should add
OnBegin = "PreparePostData()"
But since I know javascript only basically, I have no idea how can I implement this. I think this PreparePostData() should collect form fields and prepare the object routeValues parameter, to be set before the ajax call is invoked.
Anyone can give me some indications on how to implement this?
Or is any other, better approach on this problem?
Thank you
I'd recommend just writing your own AJAX calls with jQuery. It's more flexible than MVC's helpers anyway
#Html.ActionLink("Share", "Share", new { }, new { id = "share" })
And then a function
$("#share").click(function (e) {
e.preventDefault();
//Show loading display here
var form= $("#shareForm");
$.ajax({
url : '#Url.Action("Share")',
data: form.serialize(),
type: 'POST',
success: function(data){
//Show popup
$("#popup").html(data);
}
});
});
When you do have multiple Forms on same Page (imagine the case y're showing/hiding on demand), you need to add Form before the #Id as Follows :
$("#share").click(function (e) {
e.preventDefault();
//Show loading display here
// Need to add Form before #id
var form= $("Form#share");
$.ajax({
url : '#Url.Action("Share")',
data: form.serialize(),
type: 'POST',
success: function(data){
//Show popup
$("#popup").html(data);
}
});
);

Resources