ASP.NET MVC example of editing multiple child records - asp.net-mvc

Does anyone know of any examples or tutorials of an MVC view that shows parent/child data all on one form, and allows all the child records to be editable?
For example, say I have a table of people and another containing the vehicles they own. One one form, I want to show every vehicle for a given person, and make the data elements editable (i.e. license plate number, car color, etc.) in case there are mistakes. I don't want to jump to a separate edit form for each vehicle.
My attempts thus far have gotten me to the point where I can display the data, but I can't get it to post back to the controller. I've tried to narrow down the problem as far as I could here, but I'm still not getting it, and I think a broader example may be in order. Any ideas?

You can try something like this.
Suppose you have this object :
public class Vehicle
{
public int VehicleID { get; set; }
public string LicencePlate { get; set; }
public string Color { get; set; }
}
And this is your controller action that you'll use to edit vehicle details (where you'll post the form) :
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditVehicles(int Owner, Vehicle[] vehicles)
{
//manipulate the data, then return back to the list
return RedirectToAction("YourAction");
}
Then you should set your form this way :
<!--have a form for each person, listing their vehicles-->
<form action="/EditVehicles" method="post">
<input type="hidden" name="Owner" value="25" />
<input type="hidden" name="Vehicles[0].VehicleID" value="10" />
<input type="text" name="Vehicles[0].LicencePlate" value="111-111" />
<input type="text" name="Vehicles[0].Color" value="Red" />
<input type="hidden" name="Vehicles[1].VehicleID" value="20" />
<input type="text" name="Vehicles[1].LicencePlate" value="222-222" />
<input type="text" name="Vehicles[1].Color" value="Blue" />
<input type="submit" value="Edit" />
</form>
This will help the DefaultModelBinder to correctly bind the form data to your model in your controller. Thus Response.Write(vehicles[1].Color); on your controller, will print "Blue".
This is a very simple example, but I'm sure you get the idea. For more examples about binding forms to arrays, lists, collections, dictionaries, take a look at here.

I think the best you can get around this is by using AJAX posts, Whenever the user clicks on the submit button, You can hook in that event, create a JSON array of the things you want to persist and send it across.
The other way of course is to get all the information from the "FormCollection" object in the POST action. You just need to iterate through all the keys parse the data and then process it.

Related

How to insert a model view with 5 string parameters into one input

I am new in MVC and I must insert a model view with 5 string parameters into one input(type text, or instead of input it will work textarea) with decent looks (like every parameter value on a separate row). The problem is that I'm not alowed to use html helpers. Any idea? It's a response after I get all properties from previous page. So this form including the input is method="get"
model view it's like:
class phonebook
{
firstname {get;set;}
lastname {get;set;}
...
}
phonebook el;
and it must be something like:
<input type="text" value="#el"/>
I know this isn't correct, but that's the idea
try this;
<input value='#Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer()).Serialize(phonebook))'/>
I have no IDE right now but from memory:
#model AspTest.phonebook
<textarea type="text" name="allinone">#(String.Join("\r\n", Model.firstname, Model.lastname))</textarea>

ASP.NET MVC Encoding Issue

I have an ASP.NET MVC app. My app is passing a name to/from the database. I've recently discovered a bug associated with ampersands (&).
In my database, I see the name "A & W".
I am displaying this value in my UI using the following:
<input id="Name" name="Name" value="#Html.Raw(Model.Name)" />
When I view the source, I can see that the following HTML gets rendered in the browser.
<input id="Name" name="Name" value="A & W" />
So far, so good. However, when I click save, and I set a breakpoint in my controller action, I can see the Name property on my Model is now "A & W". What's worse is, everytime I save it, additional amp values get added.
How do I remedy this?
Thanks!
I had a similar problem, so I used the AllowHtml attribute on my property in my model.
[AllowHtml]
public string Name { get; set; }
If you aren't using Code First, you can apply this attribute on top of your action also:
[HttpPost]
[AllowHtml]
[ValidateAntiForgeryToken]
public ActionResult Modify(ModelClass model) {}

Exclude <input type='file'> from ViewModel

I have the following file input tag in the "Create" View:
<input type="file" id="RequestFile" name="RequestFile"/>
#Html.ValidationMessage("RequestFile")
The ViewModel contains this corresponding property:
[Required(ErrorMessage="Please select a file")]
public HttpPostedFileBase RequestFile { get; set; }
This works fine in the "Create" View, but in the "Edit" View, I get ModelState.Isvalid as false. Using the same ViewModel I would like to exclude this field from validations because I would not want to upload the file again.
I tried simply disabling the input tag like this:
<input type="file" id="RequestFile" name="RequestFile" disabled/>
This has a disabled input control but the Validation still fired.
Also applying the BindAttribute in the Controller did not work (see this Question)
Ideally (I know it sounds unlikely), if there is a server-side solution to this, please post your thoughts. If there is a small client-side trick, please let me know!
The best ways are remove the property altogether, and always access it directly from the form collection (and manually validate it) or manually remove the model state error using the property name (as #cheesemacfly has in his comment, ModelState.Remove("RequestFile")). The latter makes it very easy to fix then.
You could use form.onsubmit to check to see it document.getElementById("RequestFile").value is not null/empty and cancel the submit if it is.
something like
<form onsubmit="if(!document.getElementById('RequestFile').value){alert('Please select a file.');return false;}" >
<input type="file" id="RequestFile" name="RequestFile" />
<input type="submit"/>
</form>
return false cancels the submission.
http://jsfiddle.net/Cg7HY/1/
or put it in the click event of the submit button itself
http://jsfiddle.net/Cg7HY/3/

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.

DropDownList in conjunction with file upload in asp.net mvc

I have a file upload function in my asp.net mvc application that allows users to upload an xslx file containing data that should be persisted to a database. That data can be related to one of many categories. I need to be able to discern which category the data that is coming in is supposed to be related to, so I thought that a drop down list would be perfect for the job. However, I don't know how to get at the lists selected value when the user posts the data. This is what the code for the form looks like:
<form action="/Import/UploadFiles/" method="post" enctype="multipart/form-data">
<fieldset id="fileImport">
<legend>Importinställningar</legend>
<label for="file">Importfil:</label>
<input type="file" id="file" name="file" />
<%= Html.DropDownList("Name", (IEnumerable<SelectListItem>)ViewData["assignments"]) %>
<p>
<input type="submit" value="Spara"/>
<input type="button" value="Avbryt" onclick="window.location.href='/'" />
</p>
</fieldset>
</form>
Since I am dealing with a file upload scenario I don't have an action link that I can use to pass data to the controller, but rather an input with the type submit.
How should I go about reading the select value of the drop down list so that its selected value can be passed to the Controller?
There are a couple of different ways that you can make this work. First, add a string parameter named Name to your UploadFiles method. The default binder will fill it in from the form value with the same name. Alternatively, you can use the ValueProvider inside the controller -- if you use the same action for both rendering the view and responding to the post, for instance -- to extract the value of the parameter named Name.
public ActionResult UploadFiles( string Name )
{
...
}
or
public ActionResult UploadFiles()
{
string name = this.ValueProvider.ContainsKey("Name")
? this.ValueProvider[key].AttemptedValue
: null;
...
}

Resources