How to add data-autocomplete HTML attribute to TextBoxFor HTML helper? - asp.net-mvc-3

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")})

Related

Ajax.BeginForm not creating a form tag inside the dom

In my MVC project I'm using an ajax form to dynamically update some search results based on a modified search term.
When rendering the Ajax.BeginForm() Method, it doesn't render a <form> tag on the page (in the DOM)
everything is set up fine, Jquery, Unobtrusive and AJAX are all referenced and I have working Ajax.BeginForm instances elsewhere
#using (Ajax.BeginForm("FilterSearch","Attachment", new AjaxOptions()
{
OnComplete = "updateSearchResults",
HttpMethod = "POST"
},new{}))
{
#Html.HiddenFor(model => model.AccountId)
#Html.HiddenFor(model => model.ContactId)
#Html.HiddenFor(model => model.OpportunityId)
#Html.TextBoxFor(model => model.SearchTerm, new { placeholder = "Search Term", #class = "header-search-box" })
<input type="submit" class="header-search-input" />
}
is just rendering inside the DOM as
<input id="AccountId" name="AccountId" type="hidden" value="">
<input id="ContactId" name="ContactId" type="hidden" value="">
<input id="OpportunityId" name="OpportunityId" type="hidden" value="O6UJ9A001TB1">
<input class="header-search-box" id="SearchTerm" name="SearchTerm" placeholder="Search Term" type="text" value="">
<input type="submit" class="header-search-input">
Things to try (generally speaking):
Examine your source code (and not what the DOM is interpreting).
The DOM is based on how a browser/HTML parser interpreted the page, and now how it may actually be output. (Invalid markup will generally be suppressed, to the best of the parser's ability, and won't show up in debug tools, but will still sit on the page).
Confirm you don't have any markup mis-aligned.
Razor is smart enough to detect invalid markup, and may be cleansing output (and fixing a potential mistake), but not in a manner you were expecting.
Given this is dynamic content, make sure you're not nesting forms.
Ajax.BeginForm (and the other form helpers) supply <form>/</form> tags regardless; It's in the ctor/de-ctor methods to output those tags.
Some kind of post-processing (on the side of the AJAX processor) may be "cleansing" the output to avoid invalid HTML (e.g nested form tags). If it sees there's already a <form>, it may strip that tag from any supplemental markup being brought in.
You cannot make a form inside another form. Check your parent views to make sure you haven't accidentally started a form, and then included this partial page.
(Thanks for the tip #LiamHT)

Post ID doesn't Work in Form

I have a post where I define a new database entity. After user enters needed values and submits the form, I insert the entity and post it back to the same page and display it's ID. When I enter the ID area disabled and readonly as below, it works perfectly.
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
ID:
#Html.TextBoxFor(model => model.ID, new { disabled = "disabled", #readonly = "readonly" })
<p><input type="submit" name="submit" value="Create" /></p>
</fieldset>
}
However, when I enter it only readonly as in below, it does insert the entity, but doesn't view the ID.
#Html.TextBoxFor(model => model.ID, new { #readonly = "readonly" })
I have another submit in the form, which uses the entities ID. However, I cannot use disabled here with the ID area, as it doesn't post the ID value. What can I do to resolve the issue?
You can enable the disabled field just before submitting. So, keep the ID field disabled. Now, enable it on submit. ie; if you submit the form on "myButton" click, add this in document.ready():
$('#myButton').click(function(e)
{
e.preventDefault();
$("#ID").removeAttr('disabled');
$('form').submit();
});
Instead of using html extensions, I directly wrote:
<input type="text" name="ID" value="#Model.ID" readonly />
And it works like a charm.

How to get ID of element by using Html.BeginForm()

I have the form and some code below.
#using (Html.BeginForm("Insert", "Question", "POST"))
{
<div id="add_tag">
<div id="list_tag">
<span class="post-tag" id="2">Phi kim<span class="delete-tag" title="Xóa Tag này"></span></span>
<span class="post-tag" id="22">Hóa Vô Cơ<span class="delete-tag" title="Xóa Tag này"></span></span>
<span class="post-tag" id="1">Lý<span class="delete-tag" title="Xóa Tag này"></span></span>
</div>
<div class="tag-suggestions hidden">
</div>
</div>
<div class="form-sumit clear">
<input type="submit" id="submit-button" value="Post your question" />
</div>
}
And my Insert action in QuestionController like this
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(FormCollection _form)
{
//my code here
}
I want to get id of span tag nested in by using Html.BeginForm and FormCollection. How can I do that? Plz someone help me. Thanks a lot.
When you click on submit button, form collects all input values inside this form and send to the server with the following format: inputId=inputValue. Span isn't the input control inside the form and form does not collect its value or another information to send to the server. You can generate hidden input control and set the id value to it. And then at the server side in the action you can get it from FormCollection.
[HttpPost]
[ValidateInput(false)]
public ActionResult Insert(FormCollection formCollection)
{
//for example all hidden input controls start with "hidden_tag" id
//and end with your number of tag:
var allNeededKeys = formCollection.AllKeys.Where(x => x.StartsWith("hidden_tag"));
var listOfId = allNeededKeys.Select(formCollection.Get).ToList();
}
Good luck.
I'm pretty sure you can't. You can use fiddler to see if they're posted back to the server but I don't think they are.
You should use hidden fields to post the span's id to the server.
Is the view strongly typed?

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>

Converting a Knockoutjs HTML line to Razor syntax

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" })

Resources