I want to make an editing function where you can add metafields (= specific fields for a category) to a category.
What I want to do in the view is
foreach (App.Models.Metafield field in Model.Category.Metafields)
{
<div class="field">
#Html.TextBoxFor(model => field.Name, new { #class = "form-control title" })
#Html.DropDownListFor(model => field.Type, Model.MetaTypes, new { #class = "form-control type" })
</div>
}
The problem is that the Metafields are not added to the viewModel when I hit the save button. So I guess the field.Name and field.Type should be replaced by something else..
This can't work this way because the sent form can't contain these dynamically generated fields with the same name.
However, you can collect the data from these dynamic fields using js and serialize it into a hidden field just before submitting the form, then you can parse it in your server side.
Here is an example with jquery:
$('#save-btn').click(function(e) {
$hidden = $("#hidden");
$hidden.val(getDynamicData());
});
function getDyanmicData() {
var data;
$fields = $(".field");
// get children and calculate data
return data;
}
This may be a bit too 'manual work', but I find it useful to know what's happening. For other solutions you can search form dynamic forms in ASP.NET MVC.
Please try this code
#for(int i=0;i<=Model.Category.Metafields.count();i++)
{
<div class="field">
#Html.TextBoxFor(m=> m[i].Name, new { #class = "form-control title" })
#Html.DropDownListFor(m=> m[i].Type, Model.MetaTypes, new { #class = "form-control type" })
</div>
}
Related
I inherited an MVC site and was asked to combine two pages into one. Since both Views have their own View Model, I thought instead of pushing the two VMs together that I could use a Partial View to display, in this case, the Clock Group in a View called Clock_Detail. However, I need to get the GroupId to populate the data for the Clock Group.
So, having rarely used Partial Views I’m confused on how to get this to work.
I created a new View called _ClockGroup.cshtml and just copied and pasted some basic code from the other page just to see if I could get anything to display.
In my ClockDetail controller I added the following.
public PartialViewResult ClockGroup(int groupId)
{
ClockGroupViewModel vm = DAL.GetClockGroupDetail(groupId);
return PartialView(vm);
}
Here is _ClockGroup.cshtml
#model site.Models.ViewModels.ClockGroupViewModel
<div class="form-group">
#Html.LabelFor(m => m.GroupId, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(m => m.GroupId, new { htmlAttributes = new { #class = "form-control", disabled = "disabled", #readonly = "readonly" } })
</div>
<div class="form-group">
#Html.LabelFor(m => m.GroupName, htmlAttributes: new { #class = "control-label col-md-2" })
#Html.EditorFor(m => m.GroupName, new { htmlAttributes = new { #class = "form-control", autofocus = "autofocus" } })
#Html.ValidationMessageFor(m => m.GroupName, "", new { #class = "text-danger" })
</div>
This is from the clock_detail.cshtml view. It uses the following Model and then I added the Partial to this view.
#model site.Models.ViewModels.ClockDetailViewModel
#Html.Partial("_ClockGroup")
Of course I get an error that the model passed a dictionary type “site.Models.ViewModels.ClockDetailViewModel” but the dictionary requires a model item of time “site.Models.ViewModels.ClockGroupViewModel".
Will I need to go ahead and combine the two ViewModels together and just use the single ViewModel?
When you do not specify an object as the second parameter:
#Html.Partial("_ClockGroup")
It automatically passes the current model which is of type ClockDetailViewModel
Your partial requires type ClockGroupViewModel
The fix would be when you call the partial to pass in the ClockGroupViewModel property of your ClockDetailViewModel object:
#Html.Partial("_ClockGroup", Model.ClockGroupViewModelProperty)
If your ClockDetailViewModel class does not have a ClockGroupViewModel property, you will need to add that to your ViewModel and populate the data.
I have a lot of forms created with helper
Html.BeginRouteForm
I want to post it to my web api controller and I can do it with predefined DTO.
But I want to post it as dictionary, because the forms is for getting parameters from user. In each case the set of parameters can be different.
How I can do it?
How I can do it better?
Thanks!
UPDATE
Here is my form:
#using (Html.BeginRouteForm("DefaultApi", new { controller = "Products", action = "Add", httproute = "true" }))
{
<div class="form-group">
Product:
#Html.TextBoxFor(m => m.Product, new { #class = "form-control" })
</div>
<div class="form-group">
Cost:
#Html.TextBoxFor(m => m.Cost, new { #class = "form-control" })
</div>
}
You can declare the parameter in the post action as a FormDataCollection which is derived from NameValueCollection and is very similar to a dictionary. This is the weakly typed method to post form data in MVC.
[HttpPost]
public ActionResult Edit(FormDataCollection formDataCollection)
{
var nvc = formDataCollection.ReadAsNameValueCollection();
foreach(var key in nvc)
{
var value = nvc[key];
}
}
I have a read-only text box which is supposed to be initialized to a value dynamically. This field is present on a page which is used to enter values to details corresponding to the player that was created in the previous page (I am using RedirectToAction() for this purpose, but was unable to access the passed "PlayerID" value from the controller of the current page. So decided on using TempData. ). Since the PlayerID changes each time a new player is added, this field should display that value while still remaining read-only.
Also, this is a 'required' field, so the form cannot be submitted until the value is set.
#Html.TextBoxFor(model => model.PlayerID, htmlAttributes: new { #readonly = "read-only", #class = "control-label col-md-2", value = #Html.Raw(TempData["PlayerID"]) })
How can I set the value of this field as it is in the TempData["PlayerID"]?
You can either have a JavaScript that runs on the page load, ex:
#section Scripts
{
<script>
$(function(){
$("#PlayerID").val('#TempData["PlayerID"]');
});
</script>
}
Or, you can initialize the Model for the view inside the action, so if your action name was 'PlayerDetails', then you should have something like this:
public ActionResult PlayerDetails()
{
return View(new Player{PlayerID=TempData["PlayerID"]}
}
This way, when the view get bound to the view model, it will be initialized to the passed value.
You can try below code:
#Html.TextBox("PlayerID", #TempData["PlayerID"] ,new { #readonly = "read-only", #class = "control-label col-md-2"})
Or in your case:
#Html.TextBoxFor(model => model.PlayerId, htmlAttributes: new { #readonly = "read-only", #class = "control-label col-md-2", Value = #Html.Raw(TempData["PlayerID"]) })
I want to give a unique id to htmleditfor method. I want to add Jquery datepicker in it. Please guide...
#Html.EditorFor(model => model.AdExpiryDate, new { htmlAttributes = new { #class = "form-control", placeholder = "MM/DD/YYYY" } })
Your generated html will look like this
<input type="text" id="AdExpiryDate" value="AdExpiryDate" />
You just need to add following javascript code at bottom of your view
<script>
$('#AdExpiryDate').datepicker();
</script>
As others have said, MVC will automatically add the property name from your model to the id and name attributes on the HTML element. However if you want to specify your own id for the element, just update your htmlAttributes:
#Html.EditorFor(model => model.AdExpiryDate, new { htmlAttributes = new { #class = "form-control", placeholder = "MM/DD/YYYY", id = "ad-expiry-date" } })
Then just update your javascript to target the new id that you added:
<script>
var expireDate = $('#ad-expiry-date').val();
alert(expireDate);
</script>
Probably a simple question, but i cant seem to find the answer.
using MVC 2 i have a series of Html.ValidationFor controls. I want to assign a CSS class to the text and cant seem to do it.
<%= Html.TextBoxFor(Model => Model.Chest, new { #class = "textBoxMeasure" })%>
<%= Html.ValidationMessageFor(Model => Model.Chest) %>
if i try the same method as textboxfor i get errors because it requires a string, when i put a string in it still wont work!
thanks
I added a comment to the accepted answer, but I cannot to format it for better view. So, here is my already formatted comment from the accepted response.
I had similar case and I used solution from accepted answer. But I desired to use message from model annotation. I tried this:
#Html.ValidationMessageFor(Model => Model.Chest, null, new { #class = "text-danger" });
and it correctly worked for me. I used MVC4 with bootstrap.
There's a variant that takes htmlAttributes as the third argument (the second is the message that should be displayed, or you can use null for the default validation message)
Html.ValidationMessageFor(
Model => Model.Chest,
"Please enter a value",
new { #class = "redText" })
For more info see http://msdn.microsoft.com/en-us/library/ee721293%28v=vs.98%29.aspx
Use the classes assigned to the span tag holding the message. If the field is valid the class is field-validation-valid. If there is an error its field-validation-error.
I use
.field-validation-error {
color:Red;
}
simplest way to do this to put #Html.ValidationMessageFor in div tag and apply css to div tag
<div style="font-size:15px !important;">
#Html.ValidationMessageFor(model => model.Password, "", new { #class = "text-danger" })
</div>
This way the color range will be wider.
#Html.ValidationMessageFor(x => x.WriterName, "", new { #style = "color:red" })