Best way to do ListView in ASP.NET MVC? - c#

bascially, how should i do it now that using the asp:listview control is out of the question?
i am migrating from webforms to mvc and former implementation was in <asp:ListView...> so how should i do it now in terms of best user experience for the user? ie: i will need to ajax everything.
thanks

You should use the standard list box now. If you need to return the list from your controller you return a SelectList [i think that's it].
To ajax the select list you can use say jQuery to add click and change events which will then call actionresults in your controller.
Edit
Ah right, there are a couple of ways. You could use a jQuery grid which will display the rows and allow you to have edit delet buttons. You then post back to an action, make the changes and come back. All Ajax of course.
The other way might be to write a couple of PartialViews. The first loops through your collection and the second displays the row. The last one would have say the buttons or a check box or whatever.
Then you again post back, via ajax, to an action result, make the changes and come back.
Your action result can return a fully rendered partial view so after you make your changes, return a new partial view of your data rows and replace the old with the new.
edit 2
if you want code, leave a comment and i'll provide
edit 3
There are a bunch of jQuery grids out there, just google it.
As for partial views something like this would work;
HTML Partial View 1 called BenefitList;
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IQueryable<Models.Benefit>>" %>
<% foreach(Benefit benefit in Model){ %>
<% Html.RenderPartial("Benefit", benefit); %>
<% } %>
HTML Partial View 2;
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Models.Benefit>" %>
<fieldset class="Benefit benefit" id="<%= Model.Id %>">
<legend><label class="Title"><%= Html.Encode(Model.Title) %></label> <a class="BenefitDescriptionView" href=".">View</a><a class="BenefitDescriptionEdit" href=".">Edit</a></legend>
<div class="BenefitDescription hidden">
<%= Html.Encode(Model.Description) %>
</div>
</fieldset>
Some jQuery for you to do a post to an action result;
function jQueryDeleteBenefit() {
$.post("/Home/jQueryDeleteBenefit", { Id: YOURID },
function(NEWHTML) {
$('.EditProductContainer').html(NEWHTML);
});
}
An action result;
[AcceptVerbs(HttpVerbs.Post)]
public void jQueryDeleteBenefit(int id
{
//delete item
return PartialView("BenefitList", AllMyBenefits);
}

Related

MVC Problems 16

I am trying to post a part of my model for a view to action in another controller. I've tried to do it this way:
<% using (Html.BeginForm("Register", "User", new {createDto = Model.UserCreateDto}, FormMethod.Post))
{%>
Form code here...
<%}%>
UserCreateDto is a part of my model and it's being filled in this form. I'm trying to pass it to "Register" action in UsersController:
[HttpPost]
public ActionResult Register(UserCreateDto createDto)
The problem is that route value in Register action is null (createDto) after form submit. Maybe it is happening because route values are being attached to url before form submit event (and before model fields are filled).
Is there any way to do what I want?
UPDATE Here is the actual HTML code:
Имя пользователя
Пароль
E-mail
And here is the updated form code:
<% using (Html.BeginForm("Register", "User", FormMethod.Post))
{%>
<%: Html.HiddenFor(userCreateDto => Model.UserCreateDto.Username) %>
<%: Html.HiddenFor(userCreateDto => Model.UserCreateDto.Password) %>
<%: Html.HiddenFor(userCreateDto => Model.UserCreateDto.Email) %>
<%: Html.HiddenFor(userCreateDto => Model.UserCreateDto.Active) %>
<%= Html.LabeledValidatedTextBoxFor(username => Model.UserCreateDto.Username, true) %>
<%= Html.LabeledValidatedTextBoxFor(password => Model.UserCreateDto.Password, true)%>
<%= Html.LabeledValidatedTextBoxFor(email => Model.UserCreateDto.Email, true)%>
<input type="submit" value="Register"/>
<%}%>
Html.LabeledValidatedTextBoxFor is just my custon HTML helper.
Here is updated action signature:
[HttpPost]
public ActionResult Register(UserCreateDto userCreateDto)
userСreateDto in this action is still null.http://www.media fire.com/file/5dcrv5zupy44c0i/A16.rar/file By the way, is there any way not to use hidden fields? They are not secure enough to pass through them user registration information.
Probably what you're looking for is ModelBinding. If your UserCreateDto Model is complex enough, and by that I mean that it contains any other complex type inside, the DefaultModelBinder is not going to know how to fill your model. So you need to tell it explicitly how to map the values in your request to the Model you are expecting in the Register post method in your UserController.
This link shows an example of how to do it in ASP.NET Core. I couldn't find the ASP.NET MVC official documentation but it's not so different than this.
Hope it helps!

Call action of my controller from WebForms

Need : Call action of my controller from WebForms and set result in specific div.
My Web Application is writted in Webforms and Mvc
I need to replace in my Webforms my user control written in Webforms, with another view written in MVC.
So how call view of mvc in my webform, I must callWebforms1.Aspx, and the content must contains my view mvc and anothers views.
But without use Reponse.Redirect, because the full stream is printed, but I must print view mvc in small div.
I try to write helper which permit me print mvc view
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="WebUserControl1.ascx.cs" Inherits="MvcApplication1.WebUserControl1" %>
<% RoutingWebFormSimulator.RenderViewMvc("~/Views/Home/Index.cshtml"); %>
In my helper, I search to invoke action by reflection, but without result.
I would think the easiest way would be to pull it in via AJAX, where somePath is the URL as you would hit it (not direct to a .cshtml file like in your question). I've used a method similar to this to pull in partials into an aspx page. Can include a javascript only version if you aren't using jQuery:
<div id="example"></div>
<script>
$(document).ready(function () {
$.ajax({
url: "somePath",
success: function (data) {
$("#example").html(data);
}
});
});
</script>

MVC Html.ActionLink with post functionality?

I'm checking to see if anyone has written an MVC extension for Html.ActionLink that you can pass in Post parameters like such:
<% Html.ActionLink("Click me", "Index", "Home", new { MyRouteValue = "123" }, null, new { postParam1 = "a", postParam2 = "b" }); %>
That would render the link like normal but having an onClick event that submits an also rendered form with an Action url for the Action, Controller, and Route Values with additional hidden inputs from the Post Parameters like such:
Click me
<form id="theform" action="/Home/Index/123" method="post">
<input type="hidden" name="postParam1" value="a">
<input type="hidden" name="postParam2" value="b">
</form>
I'm looking to redirect users to various pages with potentially a lot of data. Not only from page to page, but from email to page also. This would be highly reusable and I think would clean up a lot of code, and would save a bunch of time writing this if its already floating around out there. I hate recreating the wheel when I don't have to.
ActionLink is just for creating an <a>. What you are asking for would blow up if it is already inside of a form. If it isn't then it is preferable to make the link the submit button inside the form and NOT use javascript (javascript and emails don't get along great).
You could create the form and appende it to the end of the DOM. This could be done through partial view or through javascript.
Honestly I suggest you don't use a POST. If you persist most of the data and just have the ids needed to retrieve said data, you should never have to pass too much data in an actionlink.
Ajax.ActionLink works perfectly fine for a post request. To refresh page, you can create a function that refreshes page (e.g. function reload(){ windows.location.reload();}).
It would look something like this.
#Ajax.ActionLink("DiaplyName", "Action", new { parameters to post }, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace, OnComplete="reload();"})
Note: You'll need to reference the appropriate scripts to use ajax or jQuery code.
This piece of code was helpful for me and saved my day.. I improved it and it helped me for Impersonated user.. here is bellow ,what i did..
<% if (Session["SessionUserImpersonate"] != null && Session["SessionUserImpersonate"] != "" && Session["SessionUserImpersonate"] == "Yes")
{
BLL.Models.User userold = new BLL.Models.User();
userold = (BLL.Models.User)Session["SessionUserOld"];
%>
<span class="FL">(Impersonated as <%=Website.Backoffice.SessionHelper.Session_User.UserName != null ? Website.Backoffice.SessionHelper.Session_User.UserName:"" %> , </span>
<form class="FL" id='frmid' action="/Index/Login?username=<%=userold.UserName%>&password=<%=userold.Password%>&IsImpersonate=No" method="post">
<a class="TxtRed" style="cursor:pointer;" onclick="$('#frmid').submit(); return false;" > - finish impersonated session </a>
</form>
)
<%} %>

Displaying a user control in ASP.NET MVC

This seemed easier in Web Forms; I'd have a user control, with the logic in the code-behind, and I could just drop it on a page.
But apparently code-behinds are a no-no in MVC, and the logic is in controllers. I'm a little confused about how logic for a user control is "wired up".
I want to display an RSS Feed user control. So I have a page:
<%# Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
<p>
<% Html.RenderPartial("RssFeed"); %>
</p>
</asp:Content>
I have my user control:
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewPage<SyndicationFeed>" %>
<%# Import Namespace="System.ServiceModel.Syndication" %>
<p>
<%: ViewData.Model.Title.Text %>
</p>
<div>
<% foreach (var item in ViewData.Model.Items)
{
string url = item.Links[0].Uri.OriginalString;
%>
<p><a href='<%= url %>'><b><%= item.Title.Text %></b></a></p>
<% } %>
</div>
And I have this code that I need to run to get the rss data:
using (XmlReader reader = XmlReader.Create(ConfigurationManager.AppSettings["RssFeed"]))
{
SyndicationFeed rssData = SyndicationFeed.Load(reader);
return View(rssData);
}
But where does it go? In the controller for the page that contains the control?
To sum it up, this is how you can do it
[HttpGet, ChildActionOnly]
// put this in RssController
public ActionResult RssFeed()
{
// prepare the model
SyndicationFeed rssData;
using (XmlReader reader = XmlReader.Create(ConfigurationManager.AppSettings["RssFeed"]))
{
rssData = SyndicationFeed.Load(reader);
}
return PartialView(rssData);
}
Usage:
<% Html.RenderAction("RssFeed", "Rss"); %>
And put a check into your ASCX if the Model you are sending in is null and if so, skip everything so it won't render anything. If you leave it like you have it now, it will end in an exception if the Model sent in is null.
Based on my understanding.... Yes, it can go in the controller in the page that contains the control. The partial can use the parent's ViewModel
See here (the bit on Partial Views)
http://msdn.microsoft.com/en-us/library/dd410123.aspx
EDIT
To include your RSS feed
If my controller were named RssController and it had a ViewResult method named RssFeed, I'd include the following on the .Master.
This causes the RssController to get invoked and return the view for your partial (assuming that's what View(rssData) sent back.
In ASP.NET MVC 2+, you can use Html.RenderAction to render an action's result inline.
Giving the action a [ChildActionOnly] attribute will prevent users from navigating to the action normally, making it usable only in this kind of "child" context.
I had a vaguely similar problem (using Razor view engine) which I solved by putting the code into the page since there wasn't anywhere else I wanted to put it. Mine actually related to rendering a menu.
The trick is to use the #functions { ... } construct.
Some pertinent info about the layout stuff here: http://weblogs.asp.net/scottgu/archive/2010/10/22/asp-net-mvc-3-layouts.aspx
Kind of like this in your case (not exactly right; it's late and I'm not on my dev box, but it hopefully gives the idea). That way you don't need any RSS controller at all if you are only doing this small piece of RSS related stuff.
#foreach (var item in RssFeed().Items)
{
<p><a href='#item.Links[0].Uri.OriginalString'><b>#item.Title.Text</b></a></p>
}
#functions {
public SyndicationFeed RssFeed()
{
using (XmlReader reader = XmlReader.Create(ConfigurationManager.AppSettings["RssFeed"]))
{
return SyndicationFeed.Load(reader);
}
}
}

How to declare a global variable in ASP.NET MVC page

I've began working with asp.net mvc very recently and I've ran into a problem.
I've got an aspx page which renders a few ascx pages. What I'd like to do is declare a global var at the aspx page so it is visible to all its childs. I tried <% var i = 0; %> but it wasn't visible at the child pages.
What could I do?
variables from a aspx page are not shared with the partial views.
The view is just a representation of a piece of data. You have to pass the data as a Model to each view you want to render, whether it's a plain View or a PartialView.
<% Html.RenderPartial("ViewName", Model, ViewDataDictionnary) %>
If you want to pass a variable to a partial view, I would strongly recommend you to add this parameter to the model of the partial view, rather that to pass it additionally via the ViewDataDictionnary.
You can add it to the ViewData and then pass the ViewData to the ascx with
<% Html.RenderPartial("ViewName", Model, ViewData) %>
see msdn on RenderPartial
So in your aspx page you'd do something like
<% ViewData["i"] = 0; %>
And in your userControl you'd just retrive it and use it as you want
<% int i = (int)ViewData["i"] %>
Another way would be to use RenderAction eand pass it as a parameter... so we'd need to know how you display your ascx.
see msdn on RenderAction

Categories