Model binding in Razor View (ASP.NET MVC3) at runtime - data-binding

My Index method renders a Strongly Typed View of type (InitDetails), auto generated code looks like the following:
#ModelType BookingDeamon.InitDetails
#Using Html.BeginForm()
#Html.ValidationSummary(True)
#<fieldset>
<legend>Reservation</legend>
<div class="editor-label">
#Html.LabelFor(Function(model) model.Pickup)
</div>
<div class="editor-field">
#Html.EditorFor(Function(model) model.Pickup)
#Html.ValidationMessageFor(Function(model) model.Pickup)
</div>
<p>
<input type="submit" value="Create" onclick="SubmitMe()" />
</p>
</fieldset>
End Using
On the above form, I want to display a select list box, as i'll be controlling this select list via JQuery to load different contents depending on different things.
I want to be able to deliver the value of that select list box as Pickup value.
when I try to do the following:
#Html.DropDownListFor(Function(model) model.Pickup)
I receive the following error:
Overload resolution failed because no accessible 'DropDownListFor' accepts this number of argument
Is it possible when user clicks on the submit button, instead of taking Pickup (textbox) value to the controller; it takes the value from the dropdownlist box and submit it to the controller?

try like this
#Html.DropDownListFor(ModelType=>Model.Pickup, (IEnumerable<SelectListItem>)ViewData["Pickup"],"--Select--")
in your controller
var Pickup= GetPickupList();
var PickupList= new SelectList(Pickup, "value", "Text", Pickup.DefaultSelectedValueIfAnyNeeded);
ViewData["Pickup"] = PickupList
write a function GetPickupList()
that returns a list of Pickup values.

Related

How to make the data show by filter in a razor page?

The part of the view where I filter it through Car Categories:
<div class="form-group">
<select class="form-control" id="sel1">
<option value="" disabled selected hidden>Car Styles</option>
#foreach (var item in Model.CarCats)
{
<option value="#item.CarCategoryID">#item.CarCategoryName</option>
}
</select>
</div>
The part of the view where I have cars:
#foreach (var item in Model.Cars)
{
<div class="col-lg-4">
<div class="carGalleryWrapper">
<div class="carGallery" style="background:url('#Html.DisplayFor(modelItem=>item.ImagePath)') no-repeat 0 0 ">
<div class="carDetails">
<h4>#Html.DisplayFor(modelItem => item.DailyFee) / Per Day</h4>
<h3>#Html.DisplayFor(modelItem => item.Make) #Html.DisplayFor(modelItem => item.Model), Navi, Leather, ABS</h3>
<button type="submit" class="driveMore">
#Html.ActionLink("Drive Now", "Detail", null, new { id = item.CarID }, htmlAttributes: new {})</button>
</div>
</div>
</div>
</div>
}
I want to show the cars of a category when i select it from the dropdown.
Theres a few ways of going about this
Use a form and populate a new Car list serverside (server side)
submit the form with the selected category, in your method for handling your form
remove cars from your list that dont have that category etc.
A good example of this is here
In the method that takes your page model(the method that will be posted to on form submission) that is where you would filter your car list down by category. Then return the same page.
This doesnt use js so it will always work even if your user has disabled js in their browser however its not the most user friendly due to the page reloading.
Use js to call an api that takes in a category and returns a new list of cars (client and server side)
Then repopulate your frontend with the new list
My js isnt by any stretch any good but the rough idea is to create an api controller that will take in your category and return the filtered list.
look at this answer for a start here if you look at the success response of the ajax call, it builds up html and thats what you would need to do with the filtered list returned from the api
Use js and css to hide/show cars based on the selected category (client side)
Did you have a preference?

POST URL is missing handler query string in Razor Page

I'm having an issue where my form submission url does not have a query string which points to the handler in the Code Behind. As a result I'm getting a 400 (bad request) error.
The request URL looks like this:
http://localhost:60900/EventRename
When it should look like this:
http://localhost:60900/EventRename?handler=RenameEvent
Here's the .cshtml
<form asp-page-handler="RenameEvent" method="post">
<div class="form-group">
<label asp-for="RenameDataSource"></label>
#Html.DropDownListFor(x => x.RenameDataSource, Model.DataSources, "-- select data source --")
</div>
<div class="form-group">
<label asp-for="RenameTempEvent"></label>
#Html.DropDownListFor(x => x.RenameTempEvent, Model.RenameTempEvents, "-- select event type --")
</div>
<div class="form-group">
<label asp-for="NewName"></label>
#Html.DropDownListFor(x => x.NewName, Model.EventTypes, "-- select event type --")
</div>
<div class="form-group">
<button type="submit">Start Renaming</button>
</div>
</form>
It might be related, but I've also noticed that the form data is missing the '__RequestVerificationToken', which should be included by default in Razor pages?
To clarify, I'm not expecting to see the data from the form in the URL. I'm expecting to see a handler reference so the Razor Code Behind knows which method to run when the form is submitted. See this section: https://learn.microsoft.com/en-us/aspnet/core/razor-pages/#multiple-handlers-per-page
the URL path that submits to OnPostJoinListAsync is http://localhost:5000/Customers/CreateFATH?handler=JoinList
#using (Html.BeginForm(ActionName, ControllerName, new { handler = "value of your handler" }, FormMethod.Post))
Now you can submit the form it will give you the value for the same.
your form method is post try to use get if you want to see the data string in url.
https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_and_retrieving_form_data

Passing so far entered data to controller

In a form I have different fields (name, age, ...) and the possibility to upload an image. This I want to realize on a different view. The problem is that the data, that is made so far, are not passed to the controller when I want to change the controller. Here a small example of my code:
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
<fieldset>
<legend>Person</legend>
#Html.EditorFor(model => model.Name)
#Html.EditorFor(model => model.Age)
<img src="#Url.Content(Model.ImagePath)" alt="Image" class="imagePreview" />
<li>
#Html.ActionLink("Upload a pic from you!", "UploadImage", new { model = Model }, null)
#* This is the 'problematic' action *#
</li>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Here the method that is calling the upload controller:
public ActionResult UploadImage(Person model)
{
// properties in the passed model are not set
return RedirectToAction("UploadImage", "UploadImage");
}
How it is possible to get the entered information without using the submit button?
Check out this blog post by Bryan Sampica on asynchronus file uploads with MVC. We just used it for a smooth async file upload experience so we didn't have to leave the page. This solves your problem of how to persist the transient data. If your users are using a modern browser (IE 10+, Chrome, FF, etc...) the progress bars actually show file upload progress. It's fairly easy to setup, but, if you follow the instructions to the letter, does require that you add a webAPI controller to your project.

ASP.Net MVC 4 & Unobtrusive Validation Summary

I am trying to display a summary error message on a form as well as property level errors.
The property errors get rendered using html.validationmessagefor(model =>...) which works fine.
But when there is one or more validation errors, I want html.ValidationSummary(true) to display the message "Your form is missing some details - see below".
There also might be some server side validation which will occur post submit and will be added with ModelState.AddError.
How can I get a class level dataattribute (presumably using [AttributeUsage(AttributeTargets.Class)]) to display in the summary validation using unobtrusive validation?
Is this what you are looking for:
#using (Html.BeginForm())
{
#Html.ValidationSummary(true)
#Html.ValidationSummary("Errors:")
<div>
#Html.EditorFor(model => model.PathToExcel)
#Html.ValidationMessageFor(model => model.PathToExcel)
</div>
<div>
<input type="submit" value="Load" />
</div>
}
this uses 2 ValidationSummary's, one to fill the ValidationMessageFor-fields and one to use a Summary. Summary only works after Submitting.

ASP.NET MVC: on button click, call display multiple ActionResults in different windows

I have a form that has a drop-down list of values and a submit button.
Currently, when you click on the submit button, a stored procedure is called and then the application generates a url and then the ActionResult is a Redirect to a new window. The url is based on the currently selected value in the dropdown list.
Our client wants another button that when clicked, will basically do the same thing, but FOR ALL VALUES in the drop down list.
Basically, on click, multiple windows will be opened, whose urls each based on a value in the drop down list.
I just started working with MVC and research confused me even more. I'm hoping someone can point me in the right direction.
Should I handle this via some sort of loop in javascript? How? Can you give some examples, please?
ASPX Portion:
<div id="MyContainer" class="select-report">
<%
using (Html.BeginForm(MyManager.Query.Actions.GenerateReport(null), FormMethod.Post, new{target="_blank"}))
{%>
<select name="SearchText" class="my-values-select">
<% foreach (var cc in Model.MyCentresList)
{%>
<option value="<%=Html.Encode(cc.Name) %>">
<%=Html.Encode(cc.Name) %></option>
<% } %>
</select>
<input type="hidden" name="SearchType" value="MyCentre" />
<input type="submit" value="Generate" name="EntityName" />
<% } %>
</div>
Code-Behind:
public virtual ActionResult GenerateReport(GenerateReportOperation operation)
{
string entityName = operation.SearchText;
int entityType = (int)operation.SearchType;
string requestID1 = <code here that calls a stored procedure, a value is returned>;
string requestID2 = <code here that calls a stored procedure, a value is returned>;
string urlString = <code here that contructs the URL based on the values of entityName, entityType, requestID1, requestID2>;
return Redirect(urlString);
}
You would have to use JavaScript to open new windows for each individual HTTP request.

Resources