I have a razor view where I call this:
#Html.EditorFor(m => m.Code)
Then I have an EditorTemplate view which is rendered then, it looks like this:
#model string
#Html.HiddenFor(m=>m)
And I get this output:
<input id="Code" name="Code" type="hidden" value="" />
Everything fine.
But now I just want to get the property name Code inside the EditorTemplate view, not the whole input string. The #Html.HiddenFor(m=>m) method is able to get it from the model object somehow and put it into the input field but how can I do this?
(And no, I don't want to parse it from the input field string... :)
#Html.HiddenFor(m=>m) seems kind of weird... but anyway:
HiddenFor uses Expression<Func<TModel, TProperty>> so you could make your own function to only return the name:
public static class GenericHelper<T>
{
public static String GetPropertyName<TValue>(Expression<Func<T, TValue>> propertyId)
{
var operant = (MemberExpression)((UnaryExpression)propertyId.Body).Operand;
return operant.Member.Name;
}
}
And create a helper to use that inside your view, which is explained here
Related
I am working on validation on a form in a blazor server application.
I created the component below that I am using
#* Inherits from the original InputText component *#
#inherits InputText
#* Bind the oninput event *#
<input #attributes="AdditionalAttributes"
class="#CssClass"
value="#CurrentValue"
#oninput="EventCallback.Factory.CreateBinder<string>(this, __value => CurrentValueAsString = __value, CurrentValueAsString)" />
#code {
}
I am using the inputTextOnInput in this form
<EditForm EditContext="#EditContext">
<DataAnnotationsValidator />
<div class="mb-5">
<label for="projectnameinput" class="form-label">Name your project*</label>
<InputTextOnInput class="form-control form-control-lg cust #pNameValidation" id="projectnameinput" #bind-value="projectModel.ProjectName" #onkeyup=KeyboardEventHandler />
</div>
</EditForm>
since I created this I started getting the error message below
Component attributes do not support complex content (mixed C# and markup). Attribute: 'class', text: 'form-controlform-control-lgcustpNameValidation
Do you have an idea of what this implies?
You cannot use the class attribute in your new component if you have declared a specific parameter for that.
<InputTextOnInput class="form-control form-control-lg cust #pNameValidation" id="projectnameinput" #bind-value="projectModel.ProjectName" #onkeyup=KeyboardEventHandler />
you need to remove class from above and pass it via CssClass.
For some reason Blazor/Razor don't let you mix text literals and variables within an attribute value. So when you try and do
<InputTextOnInput class="form-control form-control-lg cust #pNameValidation" id="projectnameinput" #bind-value="projectModel.ProjectName" #onkeyup=KeyboardEventHandler />
the class statement is invalid because it contains literals "form-control", "form-control-lg" and "cust" and also a variable "#pNameValidation".
My solution to this problem was to create a little method on a component base class which allows mixing the two things.
public string Class(string classStr, params string[] objStrs)
{
var output = new StringBuilder();
output.Append(classStr);
output.Append(' ');
output.AppendJoin(' ', objStrs);
return output.ToString();
}
now all I have to do is to write my line like this
<InputTextOnInput class="#Class("form-control form-control-lg cust", pNameValidation)" id="projectnameinput" #bind-value="projectModel.ProjectName" #onkeyup=KeyboardEventHandler />
and by using params, you can also just add as many string variables as you want.
I would like to create another model transferring some data from previous view. Actually I need to transfer key to save relation between objects. What are the best practices?
In my case I have one view representing a model of car and I need to start a next view representing a part containing the foreign key to the car. How to do this?
I need to transfer some attributes from one model/view to another model/view while creating. I mean passing foreign key need to keep relation in a different view(model). I tried to use the form but the web page dosen't appear to fill in the other attributes.
<form asp-action="CreateFromFirstView" asp-controller="secondControler" style="display:inline;">
<input type="hidden" name="KeyID" value="#Model.KeyID" />
<button type="submit" class="btn btn-imary">CreateFromFirstView</button>
</form>
You can create a ViewModel and send to other view the object like a Model.
Example
public ActionResult Index()
{
var vm = new VehicleDetailsViewController();
return View(vm);
}
[HttpPost]
public ActionResult Index(VehicleDetailsViewController vm)
{
//Validation something wrong
if (!ModelState.IsValid) return View(vm);
//Make what you want with all OK
return View("AllOk");
}
I am new to web development with Razor pages .net core VS 2017.
I have index page that lists my data in the form of rows & columns using EF core Model.
I am also providing data filtering options via DropDowns and search box.
I want to export this tabular filtered/unfiltered data to excel. --- For which i think i can use NPOI nuget package (http://www.talkingdotnet.com/import-export-excel-asp-net-core-2-razor-pages/).
I want to do this using asp-page-handler with button click.
Questions:
1. Will this be GET request or POST ?
How to pass data (e.g. model object with all data) to the page handler ?
Any help is Appreciated.
Thanks.
For your first question about using GET or POST, both methods can be used but I personally use the POST method for cases like this.
For your second question I would not send to server all the filtered data but I would pass the filtering information which will be used in order to generate the data and export them to an Excel file.
Update 1
I made a simple example for you. Type the following html in your cshtml file:
<form method="post">
<button type="submit" class="btn btn-info"> Export</button>
<input asp-for="Value1" type="hidden" value="1" />
<input asp-for="Value2" type="hidden" value="2" />
</form>
The two inputs will be used in order to submit to the server values which will be used in order to filter your data. The following OnPost will return a static file but you can write your own code in order to return the filtered data and return them to the browser.
[BindProperty]
public int Value1 { get; set; }
[BindProperty]
public int Value2 { get; set; }
public ActionResult OnPost()
{
// example of returning a file
return File("~/Images/accounts.png", "image/png", "FileNameForBrowser.png");
}
Thanks #pitaridis for your valuable inputs.
i ended up doing like this:
` <a asp-page="./Index" asp-page-handler="Export"
asp-route-param1 = "#Model.data1"
asp-route-param2 = "#Model.data2"
asp-route-param3 = "#Model.data3"
class="btn btn-info">
Export
</a>
`
Page handler is OnGetExportAsync(...).On handler call I am getting page refresh, Not sure Why I have to again repopulate all the controls. Any idea on this ?
or other option could be to use the OnGetAsync() method & by passing a param that identify it as file download ?
I am using MVC, Razor, Knockout, typescript in my application. Need to prepare a excel file with a model/dataset that is set at client side. I am using the following code but the problem i understand is that the dataset is being taken as string and not exactly like the model it is supposed to take as. Here is the code
This is observable (dataset)
vmExportData = ko.observableArray<ExcelModel>([]);
Push data to the dataset
vmExportData.push(new ExcelModel (
e.sender.data()[i].Id,
e.sender.data()[i].Name,
e.sender.data()[i].Address1,
));
Html code, to prepare excel file (at the controller)
#using (Html.BeginForm("ExportToExcel", "MyController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<div data-bind="css:{hidden: true}">
<input type="text" data-bind="value: vmExportData" />
</div>
<input class='excelIcon' type="submit" data-ux-access="true" value="">
}
Controller method :
public ActionResult ExportToExcel(ExportModel exportModel)
{
The problem is, the exportModel parameter value is coming as null ! Any other way out to get it to work ? Is there a way to make excel at client side and render as well ?
Try setting name="exportModel" on your tag.
Also make sure to have an [HttpPost] on top of your controller action, since your form method is post.
What does the ExportModel class look like?
how do you pass in a collection to an MVC 2 partial view?
I saw an example where they used the syntax;
<% Html.RenderPartial("QuestionPartial", question); %>
this passes in only ONE question object..
what if I want to pass in several questions into the partial view and , say, I want to list them out.
How would I pass in SEVERAL questions?
Because your partial view will usually be placed in some other (main) view, you should strongly-type your main view to a composite ViewData object that looks something like this:
public class MyViewData
{
public string Interviewee { get; set }
// Other fields here...
public Question[] questions { get; set }
}
In your controller:
var viewData = new MyViewData;
// Populate viewData object with data here.
return View(myViewData);
and in your view:
<% Html.RenderPartial("QuestionPartial", Model.questions); %>
Then use tvanfosson's advice on the partial view.
Instead of passing question, why not pass a collection of questions, for instance List<QuestionType>?
Normally, you'd have an IEnumerable<Question> as a property in your view model -- in reality it might be a list or an array of Question objects. To use it in your partial, just pass that property of the view model as the model to the partial. The partial should be strongly typed to accept an IEnumerable<Question> as it's model.
<% Html.RenderPartial("QuestionPartial", Model.Questions ); %>
Partial:
<%# Page Language="C#"
MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewUserControl<IEnumerable<Question>>" %>