ASP.NET MVC 2: What Model property datatype will autobind an html select (DDL) with multiple selections? - asp.net-mvc-2

The customer has a Model property that requires a comma separated list of selected options. We present their select list (DDL) as a multi-choice drop down.
What would the property datatype look like that would autobind multi-selections in the client side HTML select (DDL)?
The select posts data like this:
myOptions=Volvo&myOptions=Mercedes&myOptions=Audi
And we want to automagically bind it back to some property:
IList<string> CarChoices {get;set;}
So the POST action method parameter would be (Carform myForm)
which would have myForm.CarChoices which includes a List of the three selected cars?

I might be misunderstanding what you're trying to accomplish but I think this post from Phil Haack describes how to do what you're attempting to do in a clean way: http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx

Sometimes it is just easier to get your hands dirty and work with the HTML. I suggest doing something like this:
<select multiple>
<% foreach(var item in Model){ %>
<option value="<%= item.ID %>"><%= item.Description %></option>
<% } %>
</select>
obviously your model is your collection. You can also use the ViewData["Whatever"] object to pass data as well, your choice.

Related

Spring MVC 3 - custom labels in <form:select>

I'm creating a form in which user will be able to choose (among the others) the factory of a product.
Each factory is identified by and ID and has specific address.
I want to use custom label in following code:
<form:select items="${factories}" path="factory" itemValue="id" itemLabel="..."/>
At first i tried using Spring Formatter functionality (org.springframework.format.Formatter interface), but when I did this, and when I removed "itemLabel" attribute to have it displayed automatically via Formatter):
<form:select items="${factories}" path="factory" itemValue="id"/>
But then It wasn't selecting proper value if it was set (in case of editing).
Then I tried to:
<form:select path="factory" itemValue="id">
<c:forEach ...>
<form:option value="${factory.id}" label="${factory.address.city} ${factory.address.street}"
</c:foreach>
</form:select>
But as in earlier solution spring was not selecting proper value that was set in model.
My question is:
Is it possible to format entity in a way, that form:select works properly, when a value of select field is not the same as its label.
I had the same problem, the trouble is the form:option value and label maps directly to a property rather than having the flexibility to specify jstl.
So you have to hand crank the html, to something like:
<select name="factory">
<c:forEach var="factory" items="${factories}" >
<option value="${factory.id}" label="${factory.address.city} ${factory.address.street}"/>
</c:forEach>
</select>
Spring will pick up the 'path' based on the name attribute('factory' in this case), as it will try and map to the model object you are using automatically.
Another way is to add another field to the model to concatenate and format label as you wish. And if its an #Entity object then make the field #Transient.
You can also override toString() method in Factory class
#Override
public String toString() {
return "desired string";
}
Then in your jsp
<form:select items="${factories}" itemValue="id" path="factory"/>

MVC3 and Razor - How to place a dynamic value for hidden field?

I'm a beginner about Razor, and sometimes I get stuck with really simple things.
I have this foreach loop:
#foreach (dynamic item in ViewBag.EAList)
{
<li>
#using (#Html.BeginForm("Duplicate, "Daily"))
{
<p>#item.AuthorComment</p>
#Html.Hidden("EstadoDeAlmaID", #item.EAID)
#Html.Hidden("PosterID", Session["id"].ToString())
<input type="submit" value="Send" />
}
</li>
}
This line:
#Html.Hidden("EstadoDeAlmaID", #item.EAID)
Doesn't work, and I don't know how to make it work, I tried many ways, without #, with (--), with #(--)...
Could someone help me to display the dynamic value in my hidden field?
In addition, if someone know about a good Razor samples websites, I would be very thankful.
I had the same problem, found that a simple cast solved my problem.
#Html.Hidden("id", (string) ViewBag.ebook.isbn)
In Razor, once you are in "C# land", you no longer need to prefix values with # sign.
This should suffice:
#Html.Hidden("EstadoDeAlmaID", item.EAID)
Check out Scott Gu's article covering the syntax for more help.
Update
And I would also move your <li></li> within your using block, as Razor works better when you wrap HTML blocks inside of a code blocks.
Also, your Html.BeginForm should live outside of your loop.
#using (#Html.BeginForm("Duplicate, "Daily"))
{
<ul>
#foreach (? item in ViewBag.EAList)
{
<li>
<p>#item.AuthorComment</p>
#Html.Hidden("EstadoDeAlmaID", item.EAID)
#Html.Hidden("PosterID", Session["id"].ToString())
<input type="submit" value="Send" />
</li>
}
</ul>
}
Where ? in the foreach loop is the type of your items in EAList.
To avoid the Extension methods cannot be dynamically dispatched exception, use a model instead of ViewBag so you will not be using dynamic objects (this will avoid all the unnecessary casting in the View and is more in line with MVC style in general):
In your action when you return the view:
return View("ViewName", db.EAList.ToList());
In your view, the first line should be:
#model IEnumerable<EAListItem> //or whatever the type name is
Then just do:
#foreach(var item in Model)
You got the error, "Extension methods cannot be dynamically dispatched"... therein lies your trouble.
You should declare you loop variable not to be of type dynamic, but of the actual type in the collection. Then remove the # from the item.EAID call inside the #Html.Hidden() call.
The simple solution for me was to use ViewData instead of ViewBag. ViewBag is just a dynamic wrapper around ViewData anyway.
#Html.Hidden("ReportID", ViewData["ReportID"])
but I don't know if this will help in your case or not since you are creating dynamic items in your foreach loop.
I have found that when i want to use the view bag data in the HTML
Getting back to basics has often worked for me
<input type="hidden" name="Data" id="Data" value="#ViewBag.Data" />
this gave the same result.

ASP.NET MVC 2 and lists as Hidden values?

Hi,
I have a View class that contains a list, this list explains the available files that the user have uploaded (rendered with an html helper).
To maintain this data on submit I have added the following to the view :
<%: Html.HiddenFor(model => model.ModelView.Files)%>
I was hoping that the mode.ModelView.Files list would be returned to the action on submit but it is not?
Is it not possible to have a list as hiddenfield?
More information : The user submit a couple of files that is saved on the service, when saved thay are refered to as GUID and is this list that is sent back to the user to render the saved images. The user makes some changes in the form and hit submit again the image list will be empty when getting to the control action, why?
BestRegards
Is it not possible to have a list as hiddenfield?
Of course that it is not possible. A hidden field takes only a single string value:
<input type="hidden" id="foo" name="foo" value="foo bar" />
So if you need a list you need multiple hidden fields, for each item of the list. And if those items are complex objects you need a hidden field for each property of each item of the list.
Or a much simpler solution is for this hidden field to represent some unique identifier:
<input type="hidden" id="filesId" name="filesId" value="123" />
and in your controller action you would use this unique identifier to refetch your collection from wherever you initially got it.
Yet another possibility is to persist your model into the Session (just mentioning the Session for the completeness of my answer sake, but it's not something that I would actually recommend using).
Before I start I'd just like to mention that this is an example of one of the proposed solutions that was marked as the answer. Darrin got it right, here's an example of an implementation of the suggested solution...
I had a similar problem where I needed to store a generic list of type int in a hiddenfield. I tried the standard apporach which would be:
<%: Html.HiddenFor(foo => foo.ListOfIntegers) %>
That would however cause and exception. So I tried Darrin's suggestion and replaced the code above with this:
<%
foreach(int fooInt in Model.ListOfIntegers)
{ %>
<%: Html.Hidden("ListOfIntegers", fooInt) %>
<% } %>
This worked like a charm for me. Thanks Darrin.

Passing Complex object from View to Controller: one object is always null

I'm passing a complex object as a Model to the View as
but when I get the Model back from the View, one particular object comes always null while other complex types are normally passed through
my View is the default Edit Strongly Typed View
What am I missing?
The ModelState Error says
The parameter conversion from type 'System.String' to type 'Julekalender.Database.CalendarInfo' failed because no type converter can convert between these types.
Why don't I get the same for the other types? How is it automatically converted?
I have added 3 fields (as the T4 template does not append this types) but I still get null when POSTing
The green boxed below is the field
<div class="editor-field">
<%: Html.TextBoxFor(model => model.Calendar.Guid)%>
</div>
Even renaming the Action to
[HttpPost]
public ActionResult General2(GeneralInfo model)
gives the same error
Make sure that when you use this wizard there are input fields generated in the view for each property of the Calendar object so that when you post the form they will be sent to the controller action. I am not sure this is the case (haven't verified if the wizard does it for complex objects, I've never used this wizard).
In the resulting HTML you should have:
<input type="text" name="Calendar.Prop1" value="prop1 value" />
<input type="text" name="Calendar.Prop2" value="prop2 value" />
... and so on for each property you expect to get back in the post action
... of course those could be hidden fields if you don't want them to be editable
UPDATE:
The problem comes from the fact that you have a string variable called calendar in your action method and an object which has a property called Calendar which is confusing. Try renaming it:
[HttpPost]
public ActionResult General2(string calendarModel, GeneralInfo model)
Also don't forget to rename it in your view.

jQuery ajaxSubmit(): ho to send the form referencing on the fields id, instead of the fields name?

im pretty new to jQuery, and i dont know how to do that, and if it can be done without editing manually the plugin.
Assume to have a simply form like that:
<form action="page.php" method="post">
Name: <input type="text" name="Your name" id="contact-name" value="" />
Email: <input type="text" name="Your email" id="contact-email" value="" />
</form>
When you submit it, both in 'standard' way or with ajaxSubmit(), the values of the request take the label of the field name, so in the page.php i'll have:
$_POST['Your name'];
$_POST['Your email'];
Instead i'll like to label the submitted values with the id of the field:
$_POST['contact-name'];
$_POST['contact-email'];
Is there a way to do that with jquery and the ajaxsubmit() plugin?
And, maybe, there is a way to do it even with the normal usage of a form?
p.s: yes, i know, i could set the name and id attributes of the field both as 'contact-name', but how does two attributes that contain the same value be usefull?
According to the HTML spec, the browser should submit the name attribute, which does not need to be unique across elements.
Some server-side languages, such as Rails and PHP, take multiple elements with certain identical names and serialize them into data structures. For instance:
<input type="text" name="address[]" />
<input type="text" name="address[]" />
If the user types in 1 Infinite Loop in the first box and Suite 45 in the second box, PHP and Rails will show ["1 Infinite Loop", "Suite 45"] as the contents of the address parameter.
This is all related to the name attribute. On the other hand, the id attribute is designed to uniquely represent an element on the page. It can be referenced using CSS using #myId and in raw JavaScript using document.getElementById. Because it is unique, looking it up in JavaScript is very fast. In practice, you would use jQuery or another library, which would hide these details from you.
It is reasonably common for people to use the same attribute value for id and name, but the only one you need to care about for form submission is name. The jQuery Form Plugin emulates browser behavior extremely closely, so the same would apply to ajaxSubmit.
It's the way forms work in HTML.
Besides, Id's won't work for checkboxes and radio buttons, because you'll probably have several controls with the same name (but a different value), while an HTML element's id attribute has to be unique in your document.
If you really wanted, you could create a preprocessor javascript function that sets every form element's name to the id value, but that wouldn't be very smart IMHO.
var name = $("#contact-name").val();
var email = $("#contact-email").val();
$.post("page.php", { contact-name: name, contact-email: email } );
This will let you post the form with custom attributes.