Can I assign HTML values in MVC view using Html Helpers? - asp.net

Is this right? I am trying to display value in input box dynamically?
can anyone advice me is this corect approach? but still I am getting here only + + in input box?

Html.DisplayFor will render a label in this case. If you want to write in this way just use <%= Model.Date.ToString() %> for the value attribute of the input.
These HTML helpers will render the markup for you, don't try and use them as methods to return data. You can get the data by just using <%=Model.MyProperty%> as long as it is a strongy-typed view.
Try just using <%= Html.EditorFor(m => m.Date) %>
OR
<%= Html.TextBoxFor(m => m.Date) %> (the EditorFor will automatically render a textbox anyway)
OR
<%= Html.TextBox("Date", Model.Date) %> (this is not a strongly-typed helper, you're doing the data binding yourself with the second argument)

Maybe do you want this?
<input
type="text"
id="Date-<%=Model.ID%>"
value= " <%= "+" + Model.Date.ToString() + "+" %>" />
I don't know what Model is for you, but something like this might help you, if it is an object of a class that has some property Date.

Related

Rails 7 using hotwire to replace a form element

Context: a form has a collection_select, but without a value that interests the user.
A second form allows to create a new entry that would populate the collection_select with a desired value.
Class Article has_many :tags
The create turbostream does render the object, but the form does not display the change & I suspect it is due to the atomicity of the form. the IDed div tag was tried both outside and inside the form_fields tag to the same neutered effect.
<%= form.fields_for :tags do |tag| %>
<div id='tags'>
<%= f.collection_select(:tag, #tags, :id, :name) %>
</div>
<% end %>
The turbo_stream file tris to replace the target. If f.collection_select is used, this generates an error as rails, handling the snippet does not know of the form's existence. Using select_tag, a tag is rendered and delivered but the div is not refreshed
<%= turbo_stream.replace "tags" do %>
<div class='fade-in-div'>
<%= select_tag :tag, options_from_collection_for_select(#tags, :id, :name) %>
</div>
<% end %>
How can these options for select be updated with hotwire?
Functional answer that does not answer the question:
• the new data needs its own field
• make that an allowed attribute with the relevant accessor atrr_accessor
• process the new value
• update the record
• choose preferred path: redirect or turbo_stream a partial as a replacement of entire form.

Rails 4 Formatting DateTime field in partial

I'm storing a datetime field in UTC, but the user can enter it in various time zones. I configure the time zones by setting a cookie via JavaScript. Here is my ApplicationController code:
before_filter :set_timezone
def set_timezone
if !cookies["time_zone"].to_s.blank?
Time.zone = cookies["time_zone"].to_s
end
end
I'm storing the times using nested attributes on another controller's form. Here is the partial that renders to fields via simple_form and simple_fields_for, passing in the form as 'f':
<div class="row fieldset">
<div class="col-sm-3">
<%= f.input :day, collection: days, selected: f.object.day %>
</div>
<div class="col-sm-3">
<%= f.input :open, as: :string %>
</div>
<div class="col-sm-3">
<%= f.input :close, as: :string %>
</div>
<div class="col-sm-3">
<%= f.input :_destroy, as: :hidden %>
<%= link_to "remove", '#', class: "remove_fields" %>
</div>
</div>
The time zone conversion is working correctly. I can enter times in the time zone that JavaScript detects, and then it will store them in UTC. It also displays them in the detected time zone, but prints out the full format:
2014-07-22 05:00:00 -0700
I believe the fields are strings by the time they get to the view, and that's why setting the value of the input field to the following doesn't work:
<%= f.input :close, as: :string, input_html: { value: f.object.close.to_s(:short) } %>
I'm just testing the 'short' formatting option. Figured I can add a custom one later.
Do I need to format the times in the controller for the controller with the nested attributes? Or can I format them in the model that handles storing the times? Let me know if you need more information or code.
I'm not sure if these are the best options, but here are the two I found:
1) Pass an instance variable to the partial with the fields value. Instance variables allowed me to format the datetime field using to_s(:custom_format).
2) I'm using Simple Form, and found that using their time format worked well. For example:
<%= f.input :close, as: :time, ampm: true, minute_step: 15 %>
You can pass through any of the default datetime_select parameters to Simple Form.
The second option adds the meridian option (AM/PM) to the hour field, which was a little strange to me. But it seemed to be the simplest solution of the two, so I went with that for now.

MVC2 Custom Editor Template outer validation box

I've got a custom Editor Template that is essentially:
<div id="control">
<%: Html.DropDownListFor(model => model.Day, Model.Days)%>
<%: Html.DropDownListFor(model => model.Month, Model.Months)%>
<%: Html.DropDownListFor(model => model.Year, Model.Years)%>
</div>
Whilst my validation is successful/fine with this control (ValidationMessageFor works) I have been unable to find how to highlight the control when validation fails (e.g. with a TextBoxFor the textbox border goes red if validation fails)
Does anyone know how I can add this behaviour with a custom editor template please?
Interesting question. If you can detect a validation error, then you should be able to apply the appropriate class. Something like this, substitute in your own field name:
<div id = "control" class="<%=ViewData.ModelState.IsValidField("DateField") ? "" : "validation-error" %>">

MVC Html Layout C# code formatting

I insert into asp.net mvc views C# logic that manages layout like the following:
<% if (Model.People.Count > 0 ) { %>
<% foreach (var person in Model.People) { %>
...
<% }} else { %>
<span class="error">Sorry, no people</span>
<%} %>
I try to minimize <% %> code placing "{" symbol on the same line as it's condition (java-style). Html layout looks more clear to me after that.
Do you apply C# formatting rules to <% %> html injections "}" should be on a new line or manage layout in different way?
Thank you in advance!
Its totally up to you, whatever you find is more readable and maintainable.
The less inline server blocks you have the better though (in terms of preventing run-time code compilation errors).

Why can't I use an iteration variable in a LoginView?

I am building a .NET MVC app that has a page with a list of delete buttons, one for each item in a list. The problem I'm having is that the foreach variable "item" is not visible inside the LoginView, which results in the following error:
Compiler Error Message: CS0103: The name 'item' does not exist in the current context
Below is a simplified version of the view. The error occurs at the "new {id=item.Id}" in the LoggedInTemplate - the reference to "item" in the ActionLink works fine:
<% foreach (var item in Model) { %>
<%= Html.ActionLink("Item", "Details", new { id = item.Id })%>
<asp:LoginView runat="server">
<LoggedInTemplate>
<% using( Html.BeginForm( "Delete", "Items", new {id=item.Id}, FormMethod.Post))
{ %>
<input type="submit" value="Delete" runat="server" />
<% } %>
</LoggedInTemplate>
</asp:LoginView>
<% } %>
To clarify the problem is not that the Model has not been successfully passed to the View. The Model is visible from both inside and outside the LoginView. The foreach loop as no problem in iterating through the items in the Model (which is a List). The problem is that the iteration variable "item" is not accessible from within the LoginView - though the original Model is.
Is there any way to pass "item" through to the LoginView's templates? Or is building LoginViews within a foreach loops the wrong way of doing things?
Is there a scoping rule that prevents using local variables within controls - perhaps because the control is rendered at a different time to the main page?
With ASP.NET MVC you really shouldn't use user/custom controls, so if you omit the <asp:LoginView/> and write a line of code to check if the user is authenticated, you are good to go.
Instead of your current code:
<asp:LoginView runat="server">
<LoggedInTemplate>
<div>Show this to authenticated users only</div>
</LoggedInTemplate>
</asp:LoginView>
Just use an if-statement and the value of Request.IsAuthenticated:
<% if (Request.IsAuthenticated) { %>
<div>Show this to authenticated users only</div>
<% } %>
Are you passing the Model to the view and are you also inheriting from the model within that view?
So if this is a View then in your C# code you need to return the list of items like return View(listofitems);
If this is a partial view then <% Html.RenderPartial("MyPartial", listofitems) %>
And in the view you need to
<%# Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<IQueryable<ListOfItems>>" %>
If all that is in place then it should work no probs.
<% foreach (var item in Model) { %>
<%= Html.ActionLink("Item", "Details", new { id = item.Id })%>
<%= if( Request.IsAuthenticated ) {
using( Html.BeginForm( "Delete", "Items", new {id=item.Id}, FormMethod.Post))
{ %>
<input type="submit" value="Delete" runat="server" />
}
} %>
<% } %>
There is no need to use the LoginView, its not really giving you anything. Use something like the above instead.
Alternatively, you can move the decision of whether to show the delete option for the specific item into the controller, so instead of doing if( Request.IsAuthenticated ) you would do if( item.ShowDelete ) ... assuming item's type is a view model. Another option is to use an extension method for the same, item.ShowDelete(). I prefer the earlier, because there might be logic associated to deciding whether to show delete for a given item, so its better to not have it in the controller or a related logic.

Resources