ASP.NET MVC - PartialView not refreshing - asp.net-mvc

I have a user control: VendorDDL.ascx, with the following code:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<List<MeetingCalendar.Models.Vendor>>" %>
<table>
<tr>
<th></th>
<th>
VendorId
</th>
<th>
VendorName
</th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<td></td>
<td>
<%= Html.Encode(item.VendorId) %>
</td>
<td>
<%= Html.Encode(item.VendorName) %>
</td>
</tr>
<% } %>
</table>
My view: Create.aspx, has the following code snippet:
<p>
<label for="VendorNameSearch">Vendor Name:</label>
<input type="text" name="VendorNameSearch" id="VendorNameSearch" style="width:100px" />
<input type="submit" value="search" />
</p>
<% Html.RenderPartial("VendorDDL", MeetingCalendar.Controllers.HomeController.VendorsToSelect); %>
And everything works fine when I load up the Create view. The VendorDDL control is populated with the default values that are found in the VendorsToSelect. My controller has a List<Vendor> VendorsToSelect, which is getting updated properly.
Here is the problem: when the user clicks the SEARCH button, this fires off code in the Controller: return PartialView("VendorDDL", VendorsToSelect); I can see that VendorsToSelect is getting populated correctly based upon the user search.
I can step through the code, line-by-line, and see that immediately after return PartialView("VendorDDL", VendorsToSelect);, the debugger goes directly to the VendorDDL.ascx, and I can see that the Model is properly populated with the new VendorsToSelect, and the item.VendorId and item.VendorName are showing the correct values. But when debugging is done, and the Create view is shown, the VendorDDL control is not showing the new data.
Any suggestions?

I think that the output of your controller is discarded because the view (Create) has the same Html.RenderPartial("VendorDDL", MeetingCalendar.Controllers.HomeController.VendorsToSelect) as during initial load.
If I understand your problem correctly (and admittedly, without looking at the controller I may not) - you need to pass the model dynamically. The simplest (but not the most efficient) way would be to have jquery call $.load("/Home/VendorDDL") that would populate with the whole model; and then on submit hijax the form and pass form data to the same controller action.

Related

ASP.NET MVC - Delete rows in a table and then update database

In my yahoo email the inbox is displayed as a list of email items. Clicking on the item displays its detail. Now, back to the inbox. One of the columns in the list is a checkbox. If I click one or more checkboxes and then click "delete" then all those items are deleted.
That's more or less what I'd like to achieve with my ASP.NET MVC application. I have a table with some rows in it and I can tick some checkboxes to delete the selected rows and update the database.
I am coming from an Web Forms background. If the delete button is clicked it will do a post back and I can inspect in my code behind what items need to be removed. I am doing this, however, in ASP.NET MVC and I do not have the benefit of postback or view state. I figure this could be achieved with AJAX but I'd like to have a simpler solution, like a simple form post. Unfortunately, I do not know where to start.
At this point I can delete the rows on the client side with JQuery but I don't have anything on the database part as yet. Any tips is highly appreciated.
Below is my view code:
#model IEnumerable<Simplex.Data.Models.MessageBoardModel>
#{
ViewBag.Title = "Message Board";
}
<script type="text/javascript">
function deleteItems() {
$('.td_checkbox:checked').closest('tr').closest(tr).remove();
}
$(document).ready(function () {
$('#btnDelete').click(function () {
deleteItems();
});
});
</script>
<div id="content">
<h2>Board List</h2>
#{ Html.RenderAction("search", "home"); }
<div class="board_list">
<table>
<tr>
<th>
No
</th>
<th>
Subject
</th>
<th>
Posted By
</th>
<th>
Posting Date
</th>
</tr>
#foreach (var item in Model) {
<tr id=#item.Id>
<td>
#Html.DisplayFor(modelItem => item.Id)
</td>
<td class="subject">
<input class="td_checkbox" type="checkbox" /> #item.Subject
</td>
<td>
#Html.DisplayFor(modelItem => item.Username)
</td>
<td>
#Html.DisplayFor(modelItem => item.DatePosted)
</td>
</tr>
}
</table>
<button id="btnDelete">Delete</button>
<input type="button" value="Post" />
</div>
First Issue, don't use the #foreach, that strips out the built-in collection handling. Use #Html.DisplayForModel() instead. This will correctly create the proper indexed item names and id's.
Then in your HttpPost handler, you will want to have the parameter be the collection, and you can walk the list and see which checkboxes are set.
Use a for loop to render the following for each message:
<input name="messages[#i.ToString()].Key" type="hidden" value="#item.Id" />
<input name="messages[#i.ToString()].Value" type="checkbox" value="true" />
Then capture the POSTed values in your action like this
[HttpPost]
public ActionResult Delete(Dictionary<int,bool> messages)
{
IEnumerable<int> idsOfItemsYouWantToDelete = messages.Where(pair => pair.Value).Select(pair => pair.Key);
// Do delete, return redirect or whatever
}
This works because Dictionary<int,bool> is a collection of KeyValuePair<int,bool>s and the .Key and .Value input fields will be matched with the .Key and .Value properties of KeyValuePair<TKey, TValue>.
You may want to read ASP.NET Wire Format for Model Binding to Arrays, Lists, Collections, Dictionaries

asp.net mvc calling different usercontrol from different view

I Have a View Folder
FrontEnd
JobDetails.ascx (View)
Another View Folder
Job
Apply.ascx (view)
I have a Apply (a href) in jobdetails which have a show and hide div mechanism for apply (Rendering Apply.ascx in JobDetails
<div id="div1" style="visibility:hidden">
<% Html.RenderPartial("../../Views/Jobs/Create"); %>
</div>
my create View in job
<% using (Html.BeginForm("Create", "Jobs", FormMethod.Post, new { enctype = "multipart/form-data" }))
{%>
<%: Html.ValidationSummary(true) %>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td></td>
</tr>
<tr>
<td>
<% } %>
the question is that how would i go back in the JobDetails View if some Error occurs in my create form to display the errors there . I am at lost here , hope that the question is clear enough.
Probably the simplest way to handle this is to do the post of the apply via AJAX and simply render the apply form with the errors in place by replacing the existing HTML with that returned when the apply fails. If javascript is turned off, then it will render just the failed application but that seems like a reasonable trade-off to me.

Editable "GridView" like control in ASP.NET MVC

I'm trying to build a Editable GridView like control (Order column) with this code in the view:
<table>
<tr>
<th>
Name
</th>
<th>
Order
</th>
<th>
<img alt="Save order" src="<%= Url.Content("~/Content/minisave.png") %>" />
</th>
<th></th>
</tr>
<% foreach (var item in Model) { %>
<tr>
<td>
<%= Html.Encode(item.Name) %>
</td>
<td colspan="2">
<%= Html.TextBox("Order", item.Order, new { size = "3" }) %>
</td>
<td>
<%= Html.ActionLink("Edit", "Edit", new { id=item.id }) %> |
<%= Html.ActionLink("Details", "Details", new { id=item.id })%>
</td>
</tr>
<% } %>
</table>
The result table look like:
The questions are: How I receive this data in my controller? I need a form tag around the table? How I know which Order value belongs to which record?
A couple extra questions: If you see the code I add the size attribute to the input tab but when the browser renders it, the input is larger, how can I fix it?
Thanks for your help!
I've done this before. I did it by having the ID as part of the name, and a form around the entire table. That way the controller pulled all the data from all the rows and updated it all at once like a spreadsheet.
That works well for a unit of work, where you edit the page and save it, though of course you'd need to consider how to cope with your locking strategy, be it optimistic or pessimistic.
However, these days a better alternative might be to use ajax to submit specific values, somewhat like Google Spreadsheet, maybe?

How to select and pass data from the view

I'm starting to develop in ASP.NET and I can't find any example of a very simple use-case:
I've got some model objects displayed on a view.
I added a checkbox so that the user can choose the one he/she wants to see.
Then the user clicks on a link and he/she should see the model objects he/she selected displayed in another view.
1) What's the best way to get the selected items list?
At the moment I decorated my model with an IsSelected property because that's what I'd do in a ViewModel but that may not be the right answer.
2) How to pass the selected data to the next controller?
In all the examples that I've seen, data is "hardcoded" in the link and is per-object.
I haven't seen any example of a user-selection in any sample from the ASP MVC site.
EDIT: I'm afraid it wasn't that clear. What I've got is that:
<table style="width: 100%;">
<% foreach (Vehicle vehicle in Model)
{ %>
<tr>
<td>
<% 'Here be bound checkbox' %>
</td>
<td>
<%= Html.ActionLink("Show", "Index", "Map", vehicle.Name, null) %>
</td>
<td >
<%= Html.Encode(vehicle.Name) %>
</td>
<td >
<%= Html.Encode(vehicle.LastPositionReceived) %>
</td>
<td >
<%= Html.Encode(vehicle.Status) %>
</td>
<td >
<%= Html.Encode(vehicle.LocationDescription) %>
</td>
</tr>
<% } %>
</table>
By clicking on the Show link, I can already show a SINGLE item details.
Now I'd like to have the checkbox bound to a property of my model so that I can then trigger an action (with a link or a button) so that only the SELECTED items are sent to the controller.
This is the part that I haven't seen any examples about.
I could add
<% TempData.Add("Vehicles", Model); %>
somewhere and then the vehicles would be passed to the controller but I still need a way to bind the IsSelected property to the model (I don't want to hook up the Checked event and do it manually).
I hope that makes things a bit clearer.
(Thanks for the quick reply BTW ;) )
Honestly, you are not giving much information for us to give a proper answer. But here is a simple example of how you could accomplish what I think you described.
Suppose this is the part in your view where you are listing the selections to the user :
<%foreach (YourModel m in (List<YourModel>)ViewData["ModelsToList"]) {%>
<p>
<input name="selection" type="radio" value="<%=m.ID%>" id="model-<%=m.ID%>" />
<label for="model-<%=m.ID%>"><%=m.Name%></label>
</p>
<%}%>
Then you post that form to a controller action like this :
public ActionResult ShowSelectedModel(int selection) {
YourModel selectedModel = yourModelRepository.getModel(selection);
return View(selectedModel);
}
Then in your ShowSelectedModel view you can display the user's selection.
Was that what you had in mind?

Creating your own table with CommandArgument buttons in ASP.NET MVC

I'm trying to implement something like this:
<div>
<table>
<thead>
<tr>
<td>Port name</td>
<td>Current port version</td>
<td>New port version</td>
<td>Update</td>
</tr>
</thead>
<% foreach (var ip in Ports) { %>
<tr>
<td>
<%= ip.PortName %>
</td>
<td>
<%= ip.CurrentVersion %>
</td>
<td>
<%= ip.NewVersion %>
</td>
<td>
<asp:Button ID="btnUpdate" runat="server" Text="Update" CommandArgument="<% ip.PortName %>" />
</td>
</tr>
<% } %>
</table>
</div>
The button's CommandArgument property is where my code complains about not being able to resolve symbol ip. Is there any way to do what I'm trying to do?
­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
You don't want to use a Webforms button in ASP.NET MVC. MVC is a completely different way of working, and you no longer have the WebForms abstraction.
You have 2 different options you can either replace your asp:Button with an input tag or use a standard hyperlink instead. If you use the input option then you will need to wrap in a form element. The form action should point to a Controller action.
You can't use webform controls in ASP.NET MVC in a trivial manner because they rely on things that are stripped out in MVC. Instead you add a button in two ways, both using the HtmlHelper on the ViewPage:
You can add a button in a form, which is easily handeled in a controller if you have a form for each single button:
<% using(Html.BeginForm("Update", "Ip", new {portName = ip.PortName} )) { %>
....
<input name="action" type="submit" value="Update">
<% } %>
BeginForm() will default to the same controller and action as the view was created from. The other way is to add a link instead, which is more fitting to your example of iterating through a list. For example lets say you have IpController
<%= Html.ActionLink("Update IP", "Update", "Ip",
new {
portName = ip.PortName
})
%>
The link will go to the Update action in IpController with the given portName as parameter. In both cases you'll need this action in IpController:
public ActionResult Update(string portName) {
// ...
}
Hope this helps.
I think you have to enclose your block in Form tags ans runat=server.
FWIW,
I think this text is missing an equals sign:
CommandArgument="<% ip.PortName %>"
Should be
CommandArgument="<%= ip.PortName %>"

Resources