ASP MVC standard views - asp.net-mvc

ASP MVC scaffolding creates Index, Create, Update, Delete views, but how practical is that in reality. There seems to be a lot of duplication of UI code with the Create, Update and Delete views. Would it not be more practical to have one view for listing and another for Add/Edit and use some switch to format the view appropriately for Adding or Editing, and allowing deletion off the listing and edit views without redirecting to another view, instead simply popping up some sort of a "Please confirm the delete..." message?
If anyone has done something like this and is willing to share some code snippets or T4 scaffolding templates for generic cases it would be greatly appreciated.

Actually the NuGet package MvcScaffolding does exactly that, using a CreateOrEdit partial view. (See here.) The add/edit views are then created by referencing the partial view (targeting a different controller action respectively):
<fieldset>
#Html.Partial("_CreateOrEdit", Model)
<input type="submit" value="Create" />
</fieldset>
Another alternative would be to use the default MVC scaffold (as defined in the model using data annotations attributes).
<fieldset>
#Html.EditorForModel()
<input type="submit" value="Create" />
</fieldset>
As far as delete, you can always add a second mini-form at the bottom of any view (or in a list):
#{ using (Html.BeginForm("Delete", "MyController", FormMethod.Post))
{
#Html.HiddenFor(model => model.id)
<input type='submit' value='Delete' />
}
}

Related

Giving client side validation in ASP.Net MVC using Razor ViewEngine in View(.cshtml page)

I want to give client side validations for registration form in View anyhow using javascript, jQuery, or other ways to give validations client side.
And I am using strongly typed model.
my view contains code like this..
#using (Html.BeginForm())
{
#Html.LabelFor(model => model.UserName)
#Html.TextBoxFor(model => model.UserName)
<input type="submit" value="Create" id="submit" />
}
Please give solution for this...Thanks
You will need to use jQuery and jQuery Validator. Next you need to look into using DataAnnotations in your Model and mark what properties are required in your model.
See the following for a good example of setting up client side validation
http://www.codeproject.com/Articles/718004/ASP-NET-MVC-Client-Side-Validation

Removing items from list in form in ASP.NET MVC without using JS

I am trying to implement a form with a list of parameters which can be added and removed by the user. The catch is that I want to do this without javascipt. This is to be done in ASP.NET MVC 3.
I have a form like this (simplified code, so might not be quite right, it is just to illustrate what I have got):
#using (Html.BeginForm("New", "Films", FormMethod.Post, new { id = "NewFilmForm" }))
{
#if (Model.Any())
{
<!-- List of directors that have already been added -->
<div id="AddedDirectors">
#foreach (var director in Model)
{
<span>
#Html.Hidden("AddedDirectors", #director)
#Html.Raw(director)
<!-- JQuery button to remove director -->
<button class="deleteButton" type="button">x</button>
</span>
}
</div>
}
<!-- Interface for adding a new director -->
<div id="AddDirectorInterface">
<!-- Jquery show/hide add single director interface -->
<button type="button" id="AddDirectorButton">+ &nbsp Add a director</button>
<div>
#Html.TextBox("AddDirector")
<!-- Post add button -->
<button name="SubmitButton" value="#Html.Encode(NewFilmActions.AddDirector)">Add</button>
</div>
</div>
<button type="submit" name="SubmitButton" value="#Html.Encode(NewFilmActions.Save)">Save film</button>
}
I have two submit buttons here. Which are handled via a switch statement in the controller and identified via the value attribute which is set based on the NewFilmActions Enum.
Pressing the button with the AddDirector value posts to the controller, adds the name entered in the AddDirector textbox to the model and returns the view with the form again, adding the name specified by the user to the list of directors which have already been added (see commented section).
I would like to add a button allowing me to delete names which have already been added by the user...
I could put in one single button to delete all of them in one go very easily, but if posible I would like to add individual buttons. I can't figure out how to do it though.
One solution I can think off would be to append the name to the value and then in the switch statement have a default and check if the value contains a specified enum value, but that sounds a little like a botched together approach.
Can anybody either tell me how to do this or point me to some tutorial/explanations on how to implement this?
Just to emphasize: I know this can easily be done using JS, but I am looking at doing this entirely serverside for basic functionality and for my personal education.
I think you should reduce the scope of your form so it doesn't include the list.
Then you can put delete forms within you for loop, as shown below;
#foreach (var director in Model)
{
<span>
#Html.Raw(director)
#using (Html.BeginForm("Delete", "Films", FormMethod.Post, new { id = director.Id })){ <button name "DeleteButton" value="Delete">Delete</button>}
</span>
}
An example of this is also shown in this blog

create/insert multiple entities simultaneously on one view page

how to implement Create action on Order and Order Details on single Create View?
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
is there any other simpler way to do this? MVC 3 style or in Razor View? thanks so much
Using Razor as your view engine will not make the process simpler, just more readable. And even using ASP.NET MVC 3 you'll have to pretty much end up following the Editing a variable length list post that you mention.
Of course, you can add a new row of fields dynamically completely in jQuery, without having to create an action method for it. Something like:
<div id="fields">
<span class="row">
<input type="text" />
<input type="text" />
</span>
</div>
<a id="add" href="#">Add another</a>
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function() {
AddTextBox();
});
});
function AddTextBox() {
// clone the last span
var newRow = $("#fields .row:last").clone();
//clear any value the fields might have
$("input", newRow).val("");
//append it to the container div
$("#fields").append(newRow);
}
</script>
Still, the solution in the blog post encapsulates a new row of fields in a partial view which is rather clean.

Working with partial views

I'm trying to create a page that contains a grid and searching. The issue is that I want to have a partial view for the grid and one for the searching.
If doing a search, this should render the grid partial view with the new information.
At the moment I need information, such as what column I'm sorting by and so on, from the grid (currently stored in viewdata), in order to do the search as I want to keep those settings. This information is only available in the grid partial though.
What's the best approach of this to make it neat and nice in the code, but not a mess to work with?
Where can I store information that I need in the other partial view?
Partial View 1;
<table>
<%= Html.CreateGrid(Model, "Grid", "Grid", (int)ViewData["SortColumn"], (bool)ViewData["SortedASC"])%>
</table>
Partial View 2;
<div class="searchControl">
<input type="text" class="SearchBox" href="<%= Url.Action("Grid", "Grid", new {page = 1, columnToSortBy=/* would like to access viewdata from partial view 1 here. */, sortASC = /* would like to access viewdata from partial view 1 here. */ } ) %>" />
<input type="submit" value="Search" class="SearchButton" />
</div>
I know I might take the completely wrong approach on this, so feel free to point me in the right one!
Thanks!
ViewData is a good place to store data that is accessed in Views and Partials.
Even better if you use strongly typed views. Then you could access the data for sorting an filtering via a typed model.
I would have the model-classes implement an interface IGridFeatures that has properties for SortedASC, SortColumn, Page.
Its often a good idea to have these optional properties not in the route but in a querystring.
I think you'll be better of controlling your link through javascript, since all you really want is to control the UI.

performing searches with ASP.NET MVC

Ok, I've just started learning ASP.NET MVC after being an ASP.NET developer for awhile. I think my main problem I'm having is trying to "unlearn" ASP.NET when developing my MVC projects.
Here's my question: I have a page which has some input fields. These fields are parameters to a search I'm trying to run against a database. The user checks the boxes next to the types of items they want to see and then clicks "Search". Very simple stuff.
I'm having trouble wrapping my mind around how exactly to "postback" to the page to display the results. Is it better to use jQuery and serialize the form? Do I use my Entity Framework models I've created? What's the best way to go about
I'm really excited about MVC and the control it gives me, but I need to get over these initial obstacles if I ever want to "sell" it to my boss as the way to develop all of our web apps. Thanks for reading!
If you haven't already, consider taking a look at the NerdDinner Tutorial featured in Professional ASP.NET MVC 1.0 by Rob Conery, Scott Hanselman, Phil Haack, and Scott Guthrie. It contains a great demonstration of many of the features of ASP.NET MVC including performing a search and returning the data both through a full page post and also asynchronously using JSON.
If your inputs are inside html form element (different story if javascript is involved) - you can use default model binding (it binds route values and querystring parameters too).
<form ...>
<input type="text" name="query" />
<input type="submit" .../>
</form>
on submit it will automagically bind form values (by name) to action parameters:
public ActionResult PerformSearch(string query)
{
//whatever
}
In your case - i suspect you got inputs as checkboxes. Something like this should work:
<form...>
<input type="checkbox" name="p" value="value1" />
<input type="checkbox" name="p" value="value2" />
<input type="checkbox" name="p" value="value3" />
<input type="checkbox" name="p" value="value4" />
<input type="checkbox" name="p" value="value5" />
</form>
public ActionResult PerformSearch(string[] p)
{
//whatever
}
Only - if (form method == "GET"), URL won't look nicely. :)
To show results, make a model for your view in action and just show it through view:
public ActionResult PerformSearch(string[] p)
{
var model = _searchService(p);
return View("Results", model);
}
Views/Results.aspx
<% foreach(var bar in Model){ %>
<%= bar.Name %>
<%}%>
P.s. When considering AJAX calls, always remember that you are loosing ability to show URL + search engines don't understand JS.

Resources