Converting a Knockoutjs HTML line to Razor syntax - asp.net-mvc-3

I have that line :
<input type="text" data-bind="value: Price" id="Price" class="form title radius width-7"/>
How can I convert that using #Html.EditorFor (Razor) ?
Thanks

Add the appropriate validation attributes to your model property, then write
#Html.EditorFor(m => m.price, new { #class = form title radius width-7" })

Related

Asp.Net MVC 3 not binding collections to models on posting

i have a object with many properties of which one is an array of some other complex object
something like this
class obj1
{
public string prop1 {get; set;}
public string prop2 {get; set;}
public obj2[] array {get; set;}
}
class obj2
{
SomeEnum Type{get; set;}
string Content{get; set;}
}
I have created an editor template for the array of obj2 lets name it obj2ArrayTemplate
which is like this
#for (int i = 0; i < Model.Length; i++)
{
#Html.EditorFor(model=>model[i],"obj2Template")
}
and an editor template for obj2 lets name It obj2Template
which is like this
<div class="editor-label">
#Html.DisplayFor(model=>model.Type,"SomeEnum",ViewData)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Content)
#Html.ValidationMessageFor(model => model.Content)
</div>
now because property Type if of type SomeEnum which is an enum and hence cannot be rendered directly by the Asp.Net MVC
I have created a Template for this too
which is something like this
<input type="text" value="#Model.ToString()" id="#ViewData.TemplateInfo.HtmlFieldPrefix" name="#ViewData.TemplateInfo.HtmlFieldPrefix"/>
the view is being rendered correctly and the HTML of the combined rendered view is
<div class="editor-field">
<input class="text-box single-line" id="array__0__Content" name="array.[0].Content" type="text" value="FBID" />
</div>
<div class="editor-label">
<input type="text" value="Blog" id="array.[1].Type" name="array.[1].Type"/>
</div>
<div class="editor-field">
<input class="text-box single-line" id="array__1__Content" name="array.[1].Content" type="text" value="SOme random blog" />
</div>
<div class="editor-label">
<input type="text" value="Twitter" id="array.[2].Type" name="array.[2].Type"/>
</div>
<div class="editor-field">
<input class="text-box single-line" id="array__2__Content" name="array.[2].Content" type="text" value="Twitter Profile" />
</div>
when iam posting back the form containing this html
chrome is showing me this posted data
prop1:val1
prop2:val2
array.[0].Type:Facebook
array.[0].Content:FBID
array.[1].Type:Blog
array.[1].Content:SOme random blog
array.[2].Type:Twitter
array.[2].Content:Twitter Profile
but still array field which is an array of obj2 in the model of type obj1 is null
what am I doing wrong?
Could crack that one :)
inspecting the request that was being posted from the server I found out that there is one .(dot) extra in the request so the array is not being populated
so instead of
array.[0].Type:Facebook
array.[0].Content:FBID
array.[1].Type:Blog
array.[1].Content:SOme random blog
array.[2].Type:Twitter
array.[2].Content:Twitter Profile
this should be posted back
array[0].Type:Facebook
array[0].Content:FBID
array[1].Type:Blog
array[1].Content:SOme random blog
array[2].Type:Twitter
array[2].Content:Twitter
and I found no apparent reason of why Asp.Net MVC framework is putting in that extra dot. when im kind of doing everything the MVC way
so I changed my code to include a little hack.
I added this like to the Editor template of obj 2
#{
ViewData.TemplateInfo.HtmlFieldPrefix = ViewData.TemplateInfo.HtmlFieldPrefix.Replace(".", "");
}
so now everything is running fine and smooth.

MVC3 : data retrived from ViewData contains "/"

I have a small problem. I'm passing a id from one view to another.
I do it like this:
#Html.Partial("DetailViews/_Parameters", Model.Parameters, new ViewDataDictionary { { "data-resourceId", Model.Id } })
I use this id for a hidden field in a form on the partial view. like this:
<form id="formAddNewParameter" action"#" title="Add new Parameter">
<input type="hidden" name="resourceId" id="resourceId" class="required" rel="0" value=#ViewData["data-resourceId"]/>
</form>
The ID is passed as it should. BUT there is always a "/" at the end...
Anyone know where this "/" comes from.
You are missing the qutation marks "" around the value tag's value
<form id="formAddNewParameter" action"#" title="Add new Parameter">
<input type="hidden" name="resourceId"
id="resourceId" class="required" rel="0"
value="#(ViewData["data-resourceId"])" />
</form>
And I guess the tag closing / somehow mixed into the value tag.

Asp.Net MVC Strongly Typed Collections. EditorFor not appending generated prefix

I'm using this tutorial at the moment.
(I believe my issue is related to strongly typed collections... by what I've been seeing on the internet, but I could be wrong)
Please bear with me. :)
I've been having this issue which I asked in another question, the answer seemed fine, but after tinkering with the code a bit more I realized that the issue is that the fields that make use of my custom partial view, don't get a prefix added to them like the fields that use a TextBoxFor html helper, for example. EG. When I click on add a new item, it adds it, but with the same ID as an item that's been added before, then my Javascript fails because there's two items with the same id.
Some code to try and clarify the issue
Partial View
#model Portal.ViewModels.Micros
#using Portal.Helpers
<div class="editorRow" style="padding-left:5px">
#using (Html.BeginCollectionItem("micros"))
{
#Html.EditorFor(model => model.Lab_T_ID)
#Html.EditorFor(model => model.Lab_SD_ID)
#Html.TextBoxFor(model => model.Result)
<input type="button" class="deleteRow" title="Delete" value="Delete" />
}
</div>
The TextBoxFor (Result) gets rendered as
<input id="micros_5e14bae5-df1b-4c42-9e96-573a8e52f8b2__Result" name="micros[5e14bae5-df1b-4c42-9e96-573a8e52f8b2].Result" type="text" value="">
Editor For get rendered as
<select id="Lab_SD_ID" multiple="multiple" style="width: 300px; display: none; " >
<option value="5" selected="selected">Taken at Packing 1</option>
<option value="6">Taken at Packing 2</option>
<option value="7">Taken at Packing 3</option>
</select>
<button type="button" class="ui-multiselect ui-widget ui-state-default ui-corner-all" aria-haspopup="true" tabindex="0" style="width: 300px; ">
<span class="ui-icon ui-icon-triangle-2-n-s"></span><span>Taken at Packing (Winc 4/5-25d)</span></button>
I can include more code if its needed, there is a helper class as well (BeginCollectionItem), that I used which is located in the demo project in the tutorial as well.
I basically need to find out how "micros[5e14bae5-df1b-4c42-9e96-573a8e52f8b2]." gets appended to the input boxes as far as I can see, but have been stumped by it so far :/
The reason this works with TextBoxFor and not your custom EditorFor is because the TextBoxFor helper respects the template navigational context whereas in your editor template you have simply hardcoded a <select> element that doesn't even have a name. I would recommend you to use HTML helpers when generating input fields:
So replace your hardcoded select in the custom template with:
#model int?
#{
var values = ViewData.ModelMetadata.AdditionalValues;
}
<span>
#Html.DropDownList(
"",
Enumerable.Empty<SelectListItem>(),
new {
multiple = "multiple",
style = "width:" + values["comboboxWidth"] + "px",
data_url = Url.Action((string)values["action"], (string)values["controller"]),
data_noneselectedtext = values["noneSelectedText"],
data_value = values["id"],
data_text = values["description"]
}
)
</span>

How to add data-autocomplete HTML attribute to TextBoxFor HTML helper?

autocomplete text box for getting city autocomplete textbox.
My code look like this,
<input id="location" type="text" name="q"
data-autocomplete="#Url.Action("locationSearch", "Home",
new { text = "location" })"/>
Now i want to convert this to razor syntex. I tried this but not working.
#Html.TextBoxFor(model => model.Location,
new { data-autocomplete = Url.Action("locationSearch", "Home")})
How can i solve this??
data-autocomplete is an HTML attribute. First of all you can't use dashes when specifying attributes in MVC, therefore you need to replace your data-autocomplete with data_autocomplete. MVC is "smart enough" and final result will read data-autocomplete.
To add an HTML attribute to your text input you need to use the following HTML helper:
#Html.TextBoxFor(model => model.Location, new { data_autocomplete = Url.Action("locationSearch", "Home") })
Please work on your acceptance rate.
u can just use this
in your view
<select id="location" name="location"></select>
<input type="submit" value="Send">
that is actually dropdownlist, not textbox, they edit the layout via css
You should use undescore symbol in HtmlAttributes argument:
#Html.TextBoxFor(model => model.Location, new { data_autocomplete = Url.Action("locationSearch", "Home")})

MVC3 Razor Partial view render does not include data- validation attributes

I have a farily straight forward form that renders personal data as a partial view in the center of the form. I can not get client side validation to work on this form.
I started chasing down the generate html and came up with the same model field rendered on a standard form and a partial view.
I noticed that the input elements are correctly populated on the first call, #html.partial, the following only happens when the partialview is reloaded via an ajax request.
First the header of my partial view, this is within a Ajax.BeginForm on the main page.
#model MvcMPAPool.ViewModels.EventRegistration
<script src="#Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function ()
{
$(".phoneMask").mask("(999) 999-9999");
});
</script>
#{
var nPhn = 0;
var dTotal = 0.0D;
var ajaxOpts = new AjaxOptions{ HttpMethod="Post", UpdateTargetId="idRegistrationSummary", OnSuccess="PostOnSuccess" };
Html.EnableClientValidation( true );
Html.EnableUnobtrusiveJavaScript( true );
}
Here is the razor markup from the partial view:
#Html.ValidationMessageFor(model=>Model.Player.Person.Addresses[0].PostalCode)
<table>
<tr>
<td style="width:200px;">City*</td>
<td>State</td>
<td>Zip/Postal Code</td>
</tr>
<tr>
<td>#Html.TextBoxFor(p=>Model.Player.Person.Addresses[0].CityName, new { style="width:200px;", maxlength=50 })</td>
<td>
#Html.DropDownListFor(p=> Model.Player.Person.Addresses[0].StateCode
, MPAUtils.GetStateList(Model.Player.Person.Addresses[0].StateCode))</td>
<td>
<div class="editor-field">
#Html.TextBoxFor(p=>Model.Player.Person.Addresses[0].PostalCode, new { style="width:80px;", maxlength=10 })
</div>
</td>
</tr>
</table>
Here is the rendered field from the partial view:
<td>
<div class="editor-field">
<input id="Player_Person_Addresses_0__PostalCode" maxlength="10" name="Player.Person.Addresses[0].PostalCode" style="width:80px;" type="text" value="" />
</div>
</td>
Here is the same model field rendered in a standard view:
<div class="editor-field">
<input data-val="true" data-val-length="The field Postal/Zip Code must be a string with a maximum length of 10." data-val-length-max="10" data-val-required="Postal or Zip code must be provided!" id="Person_Addresses_0__PostalCode" maxlength="10" name="Person.Addresses[0].PostalCode" title="Postal/Zip Code is required" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="Person.Addresses[0].PostalCode" data-valmsg-replace="true"></span>
</div>
Notice that the partial view rendering has no data-val-xxx attributes on the input element.
Is this correct? I do not see how the client side validation could work without these attributes, or am I missing something basic here?
In order to create the unobtrusive validation attributes, a FormContext must exist. Add the following at the top of your partial view:
if (this.ViewContext.FormContext == null)
{
this.ViewContext.FormContext = new FormContext();
}
If you want the data validation tags to be there, you need to be in a FormContext. Hence, if you're dynamically generating parts of your form, you need to include the following line in your partial view:
#{ if(ViewContext.FormContext == null) {ViewContext.FormContext = new FormContext(); }}
You then need to make sure you dynamically rebind your unobtrusive validation each time you add/remove items:
$("#form").removeData("validator");
$("#form").removeData("unobtrusiveValidation");
$.validator.unobtrusive.parse("#form");

Resources