Ajax Img Upload Parameter Is Invalid Asp Net Mvc
Introduction
Many web developers are challenged to design user interfaces that provide an interactive experience while collecting data from users and dynamically creating new page elements.
The collection of technologies known as AJAX (Asynchronous JavaScript and XML) provides a mode for spider web applications to asynchronously transport and receive data from a server without the demand to refresh the page or interfere with its appearance. By decoupling the presentational layer from the data exchange layer, AJAX (or Ajax) enables web applications to dynamically change content without reloading the entire page.
Ajax has enabled many enhancements to website user interfaces as support for Ajax has go more extensive in modern web browsers. Support for Ajax in the widely-used jQuery JavaScript library has simplified Ajax implementation.
Microsoft provides support for Ajax functionality in ASP.Internet MVC through classes in the System.Web.Mvc and System.Web.Mvc.Ajax namespaces. Ane of the principal classes in this group is AjaxHelper<TModel>
which, as Microsoft puts information technology, "includes methods that provide client-side functionality in ASP.NET AJAX in MVC applications, such as creating asynchronous forms and rendering links. The AjaxHelper grade supports asynchronous partial-folio updates."
The instance written report presented in this guide uses one AjaxHelper class method, BeginForm
, to provide the asynchronous functionality needed to update a section of a web page without refreshing the entire page. The residue of the functionality comes from basic ASP.NET MVC components like controller deportment and partial views.
Case Study Clarification
The examples shown in this guide are derived from a case study projection available on GitHub. You tin can download and run the project to run across the techniques illustrated here in action and to experiment on your own.
The case study is a multi-project Visual Studio 2017 solution developed from the default ASP.Net .Net Framework MVC template. It uses Entity Framework 6.1 and the repository and Model View ViewModel (MVVM) design patterns.
The solution consists of iii projects that institute the dissimilar layers of the application:
Project | Awarding Layer |
---|---|
Blip.Information | Information Context and Repositories |
Bleep.Entities | Data Entities |
Bleep.Web | User Interface (views) and Business concern Logic (controllers) |
The case study application BlipAjax is a simple organisation for gathering, storing, and retrieving geographic and other data nigh customers. Information technology's not product-fix from either the blueprint or coding perspectives; it exists to illustrate the concepts discussed in this guide.
More importantly, Entity Framework and the repository and MVVM blueprint patterns are production-fix tools. The example projection was constructed so yous can start with the MVC template and put together your ain solutions using these resources using the sample project as a guide.
Entities
The construction of the BlipAjax entities is simple, at that place are customers, which are located in a specific state and region. They can accept multiple due east-mail addresses and multiple postal addresses. Postal addresses are similarly located in countries and regions. The entity-human relationship diagram looks like this:
The Seed
method of the Configuration
grade in Bleep.Information.Migrations
contains data for populating the lists of Countries and Regions.
Screenshots
The user interface for BlipAjax is as simple as the information model. Since the awarding is built on the MVC default template, the dwelling house page looks nearly identical:
There is a new heading and push for the customer database functionality:
Selecting Edit at the end, for a client, opens the customer edit page. It's this folio that implements the Ajax functionality described in this guide.
The Address Type drop-down enables the user to select either "E-mail" or "Postal" address. When the user presses "Select", the Ajax HTTP POST functionality of the related partial view, AddressTypePartial.cshtml
, is activated and the page is updated with either the partial view for creating an electronic mail address, CreateEmailAddressPartial.cshtml
, or CreatePostalAddressPartial.cshtml
, the partial view for creating a postal accost.
This is the Edit Customer Information view with the due east-mail address pick selected:
And this is what Edit Client Information looks like with the postal address option selected:
Code Intro
ASP.NET MVC Ajax Helper classes provide functionality like to that of a client-side framework without imposing the development overhead. With relatively little C#, a developer can create flexible, responsive user interface elements.
Components Summary
Separation of concerns and the constraint that HTML pages cannot have nested views both dictate that the Customer/Edit view cannot accept its ain view model. Instead, each course department of the view is equanimous of a partial view with its ain view model.
In BlipAjax, the accompanying example solution, the awarding tiers are located in unlike projects, as follows:
Application Tier | Project | Component |
---|---|---|
User Interface Presentation | Blip.Web | Views |
User Interface Information | Blip.Entities | ViewModels |
Business organisation Logic | Bleep.Web | Controllers |
Data Entities | Blip.Entities | Models |
Information Interface | Blip.Data | Repositories |
Data Store | Blip.Data | Information Context |
Although in that location are a number files that comprise the single page Client/Edit folio, the relationship of the files is easy to discern.
View and Partial Views (.cshtml)
Project | Binder |
---|---|
Bleep.Web | Views/Client |
Component | File |
---|---|
Customer/Edit parent view | Edit.cshtml |
Customer information fractional view | EditCustomerPartial.cshtml |
Address type selection partial view | AddressTypePartial.cshtml |
E-mail address partial view | CreateEmailAddressPartial.cshtml |
Postal address partial view | CreatePostalAddressPartial.cshtml |
Note that in the instance application but one of the address partial views appears on the page at one time, either the e-mail partial view or the postal address partial view.
View Models Summary
Project | Folder |
---|---|
Blip.Entities | Customers.ViewModels |
Component | File |
---|---|
Customer/Edit parent view | (none) |
Customer information partial view | CustomerEditViewModel.cs |
Address blazon selection fractional view | AddressTypeViewModel.cs |
Electronic mail address partial view | EmailAddressViewModel.cs |
Postal address fractional view | PostalAddressEditViewModel.cs |
Controller Methods Summary
Project | Folder | File |
---|---|---|
Blip.Web | Controllers/Customers | CustomerController.cs |
Associated Partial View | Method | HTTP Action | Parameter(s) |
---|---|---|---|
Edit.cshtml | Edit | GET | cord customerid |
EditCustomerPartial.cshtml | EditCustomerPartial | Go | string customerid |
EditCustomerPartial.cshtml | EditCustomerPartial | POST | CustomerEditViewModel |
AddressTypePartial.cshtml | AddressTypePartial | Become | string customerid |
AddressTypePartial.cshtml | AddressTypePartial | Post | AddressTypeViewModel |
CreateEmailAddressPartial.cshtml | CreateEmailAddressPartial | Postal service | EmailAddressViewModel |
CreatePostalAddressPartial.cshtml | CreatePostalAddressPartial | Postal service | PostalAddressEditViewModel |
Note that there is no signature associated with the Edit
method. This is because all the HTTP POST activeness associated with the Edit
view takes place in the POST deportment of the partial views:
-
CreateEmailAddressPartial
-
CreatePostalAddressPartial
Annotation also that CreateEmailAddressPartial
and CreatePostalAddressPartial
only have signatures for HTTP Post considering the Postal service action of AddressTypePartial
performs the function of invoking the Razor engine for the electronic mail address and postal address partial views.
Views and Fractional Views
Blip.Spider web/Views/Customer/Edit.cshtml
The lawmaking for the parent view is quite straightforward. Note the following:
-
There is no
@model
Razor directive: as noted in the code, the view models exist in the partial views. -
The
@Html.Activity
HtmlHelper is used to return ii partial views when the Edit view is get-go rendered. The HtmlHelper invokes the corresponding HTTP Become action in CustomerController.cs. -
The HTTP GET controller methods associated with the partial views require the current value of
CustomerID
to recollect and render the appropriate information. This value is too the route value for the view, only it could also be passed in theViewBag
collection when the Edit view is called from the Alphabetize view. Judicious apply of route values and data passed in theViewBag
orViewData
collections can serve the same role as data that might otherwise exist bound in the data model. -
An empty HTML element is used as the target for the Ajax action that renders either the e-postal service address or postal accost fractional view.
<div id="CreateAddress"></div>
1 @*Models are in partial views.*@ ii three@section header { 4 5} six 7@{ 8 ViewBag.Championship = "Edit Client Information"; 9} ten eleven < div form = " row " > 12 < div class = " col-md-12 " > 13 < h2 > Edit Customer Information </ h2 > 14 </ div > 15 </ div > 16 17 < div id = " EditCustomerPartial " > 18 @Html.Activeness("EditCustomerPartial", new { id = Url.RequestContext.RouteData.Values["id"] }) xix </ div > 20 21 < div id = " SelectAddressTypePartial " > 22 @Html.Action("AddressTypePartial", new { id = Url.RequestContext.RouteData.Values["id"] }) 23 </ div > 24 25 < div id = " CreateAddress " > </ div > 26 27 < div grade = " row " > 28 < div form = " course-group " > 29 < div grade = " col-doctor-12 " > 30 < hr /> 31 < div > 32 @Html.ActionLink("Back to Listing", "Index") 33 </ div > 34 </ div > 35 </ div > 36 </ div > 37 38@section Scripts { 39 @Scripts.Return("~/bundles/jqueryunobtrusive") @*For unobtrusive-ajax*@ 40 @Scripts.Render("~/bundles/jqueryval") @*For validate and validate-unobtrusive*@ 41... 42}
html
The JavaScript represented past the ellipses higher up provides functionality for the drop-down lists and does not effect the Ajax functionality. That topic is one for a carve up tutorial. The complete lawmaking can be seen in the instance project on GitHub.
JavaScript for AjaxHelper Methods
The Scripts
section of Edit.cshtml contains a reference to a JavaScript bundle that is essential for the Ajax functionality. The jqueryunobtrusive
package includes the script library jquery.unobtrusive-ajax.js (or jquery.unobtrusive-ajax.min.js in Release style).
The jQuery library itself must exist loaded before the unobtrusive-ajax library. This is done past this portion of the _Layout.cshtml shared view:
1 ... two @Scripts.Render("~/bundles/jquery") iii @Scripts.Render("~/bundles/bootstrap") iv @RenderSection("scripts", required: imitation) five...
html
Including the reference to ~/bundles/jqueryunobtrusive
in the scripts
section of the Edit.cshtml folio ensures the Ajax library gets loaded after the jQuery library and merely gets loaded on the page where it is used.
Blip.Web/Views/Customer/EditCustomerPartial.cshtml
Aside from being a partial view, EditCustomerPartial.cshtml contains all the standard features of a data-driven Razor view:
-
A model bound with the
@model
Razor directive. -
An HTML form section created with the
HtmlHelper.BeginForm
method.Annotation that the signature used identifies the partial view, controller name, and HTTP form method.
-
Form controls leap to the view model.
- A submit button for the form.
Notation that it as well has a code section where the value of the Layout
attribute of the view is fix to zilch
. This addresses a problem where in which the Razor rendering engine can apply all the features of the _Layout.cshtml file, commonly found in the Shared folder, to partial views when the outset partial view encountered has a bound data model merely the parent view does not. Setting this value to aught
forces the Razor engine to return the partial view as a partial view.
1 @model Blip.Entities.Customers.ViewModels.CustomerEditViewModel ii 3@{ 4 Layout = goose egg; 5} six vii@using (Html.BeginForm("EditCustomerPartial", "Client", FormMethod.Post)) 8{ 9 @Html.AntiForgeryToken() 10 < div class = " course-horizontal " > 11 < hr /> 12 < h4 > Edit customer details </ h4 > 13 @Html.ValidationSummary(true, "", new { @course = "text-danger" }) 14 < div class = " form-group " > fifteen @Html.LabelFor(model => model.CustomerID, htmlAttributes: new { @form = "control-label col-md-2" }) sixteen < div class = " col-md-10 " > 17 @Html.EditorFor(model => model.CustomerID, new { htmlAttributes = new { @class = "form-control", @readonly = "readonly" } }) 18 </ div > xix </ div > 20... 21 < div form = " form-group " > 22 < div grade = " col-physician-offset-two col-medico-x " > 23 < input blazon = " submit " value = " Save " class = " btn btn-primary " /> 24 </ div > 25 </ div > 26 </ div > 27}
html
Because the submit button is associated with the HTML course defined in this partial view, its activeness and the data associated with it are specific to this <form>
element within the page.
Blip.Web/Views/Client/AddressTypePartial.cshtml
The partial view for selecting the address type to add (east-mail or postal) is besides simple and is, for the about office, like to a conventional information-backed view. The of import differences are in how the <class>
element is generated and, as a result, what happens with the submit button is pressed.
-
The HTML
<grade>
element is generated with theAjax.BeginForm
helper method rather than anHtml.BeginForm
helper method. -
The first argument,
"AddressTypePartial"
, identifies the partial view that contains the class. - The second argument consists of an
AjaxOptions
object with the following properties:
Property | Value | Clarification |
---|---|---|
HttpMethod | POST | The HTTP action that will occur when the submit button is pressed. |
UpdateTargetId | CreateAddress | The element of the parent form (Edit.cshtml) to be acted on past the effect of the POST action. |
InsertionMode | InsertionMode.Replace | What will be done with the results of the POST activeness in relation to the target chemical element. |
ane @model Blip.Entities.Customers.ViewModels.AddressTypeViewModel 2 3@using (Ajax.BeginForm("AddressTypePartial", new AjaxOptions { HttpMethod = "POST", UpdateTargetId = "CreateAddress", InsertionMode = InsertionMode.Replace })) 4{ 5 @Html.AntiForgeryToken() 6 < div form = " form-horizontal " > 7 < hr /> viii < h4 > Select an accost blazon to add </ h4 > 9 @Html.ValidationSummary(true, "", new { @class = "text-danger" }) x @Html.HiddenFor(model => model.CustomerID) 11 < div class = " grade-group " > 12 @Html.LabelFor(model => model.SelectedAddressType, htmlAttributes: new { @class = "command-characterization col-md-2", id="AddressTypeLabel" }) 13 < div class = " col-dr.-10 " > fourteen @Html.DropDownListFor(model => model.SelectedAddressType, new SelectList(Model.AddressTypes, "Value", "Text"), htmlAttributes: new { @class = "form-control", id="AddressType" } ) 15 @Html.ValidationMessageFor(model => model.SelectedAddressType, "", new { @class = "text-danger" }) 16 </ div > 17 </ div > 18 nineteen < div class = " form-group " > 20 < div grade = " col-doc-offset-2 col-md-10 " > 21 < input type = " submit " value = " Select " class = " btn btn-primary " /> 22 </ div > 23 </ div > 24 </ div > 25}
html
Notation that an Html.AntiForgeryToken()
method call is included for each fractional view.
Too note that neither partial view contains JavaScript. Scripts are located in the parent form, with ane exception discussed in the companion tutorial on using JavaScript with Ajax partial views.
Rendered HTML
The generated HTML rendered past the browser for the Client/Edit view appears below. Information technology is worth studying the client-side HTML closely because doing so makes the relationship between the fractional views, the <class>
elements, and the controller actions clearer.
Note the post-obit features of the HTML:
-
There are two
<form>
elements, one each in the elements corresponding to the fractional views:<div id="EditCustomerPartial">
<div id="SelectAddressTypePartial">
-
Each form has an anti-forgery token.
-
Each form has a HTTP POST action that points to the controller method signature corresponding to the POST method for the associated partial view.
-
The
SelectAddressTypePartial
form element includes Ajax attributes that specify the actions to perform when the Post action returns from the server, including specifying the replacement of theCreateAddress
element. -
The
<div id="CreateAddress"></div>
element exists inside the<body>
chemical element, but exterior either of the<grade>
elements. - The
<script>
includes at the bottom of the page include jquery-iii.2.1.js and jquery.unobtrusive-ajax.js, the two libraries essential for the AjaxHelper classes.
Ellipsis ( ...
) indicates code has been redacted for brevity.
localhost:61621/Client/Edit/68f8202d-21cb-4090-a86c-0722bf588d1b
1 <! DOCTYPE html > two < html > 3 < head > 4 < meta charset = " utf-8 " /> v < meta proper noun = " viewport " content = " width=device-width, initial-scale=one.0 " > six < title > Edit Customer Information - My ASP.NET Application </ title > 7 < link href = " /Content/bootstrap.css " rel = " stylesheet " /> 8 < link href = " /Content/site.css " rel = " stylesheet " /> 9 < script src = " /Scripts/modernizr-2.eight.iii.js " > </ script > 10 </ head > 11 < body > 12 < div class = " navbar navbar-changed navbar-stock-still-acme " > 13 ... 14 </ div > fifteen < div grade = " container body-content " > 16 < div class = " row " > 17 < div form = " col-md-12 " > 18 < h2 > Edit Customer Information </ h2 > 19 </ div > 20 </ div > 21 < div id = " EditCustomerPartial " > 22 < form activeness = " /Customer/EditCustomerPartial/68f8202d-21cb-4090-a86c-0722bf588d1b " method = " post " > 23 < input proper noun = " __RequestVerificationToken " type = " hidden " value = " rN4xA8UDIHeo8YHYFZ4Bnc16Fr6oQdjpnV0hKPNpgHcMHNe5ZyE7tCP5ouWG3OyRGI8a9ihfpoaonfd1pf5o-RcQuG7049hNX0cKSTuNE0I1 " /> 24 < div form = " form-horizontal " > 25 < hr /> 26 < h4 > Edit customer details </ h4 > 27 < div class = " form-group " > 28 < characterization course = " control-label col-md-2 " for = " CustomerID " > Customer Number </ label > 29 < div class = " col-md-x " > thirty < input grade = " form-control text-box single-line " id = " CustomerID " name = " CustomerID " readonly = " readonly " type = " text " value = " 68f8202d-21cb-4090-a86c-0722bf588d1b " /> 31 </ div > 32 </ div > 33 < div class = " form-grouping " > 34 < characterization class = " command-label col-physician-ii " for = " CustomerName " > Customer Proper name </ characterization > 35 < div class = " col-md-10 " > 36 < input class = " form-control text-box single-line " data-val = " true " information-val-length = " The field Customer Proper name must be a string with a maximum length of 75. " data-val-length-max = " 75 " data-val-required = " The Customer Proper name field is required. " id = " CustomerName " name = " CustomerName " type = " text " value = " Spacely Space Sprokets " /> 37 < span class = " field-validation-valid text-danger " data-valmsg-for = " CustomerName " data-valmsg-replace = " true " > </ bridge > 38 </ div > 39 </ div > twoscore < div class = " course-group " > 41 < characterization class = " control-label col-doctor-2 " for = " SelectedCountryIso3 " > State </ label > 42 < div class = " col-md-10 " > 43 < select course = " form-control " data-val = " true " data-val-required = " The State field is required. " id = " Country " name = " SelectedCountryIso3 " > 44 < option value = " " > --- select country --- </ pick > 45 < option value = " CAN " > Canada </ option > 46 < pick value = " FRA " > France </ option > 47 < selection selected = " selected " value = " USA " > United States of America </ choice > 48 </ select > 49 < span class = " field-validation-valid text-danger " information-valmsg-for = " SelectedCountryIso3 " data-valmsg-supplant = " truthful " > </ span > l </ div > 51 </ div > 52 < div class = " class-group " > 53 < label class = " control-label col-md-2 " for = " SelectedRegionCode " > State / Region </ label > 54 < div class = " col-md-10 " > 55 < select course = " form-command " data-val = " true " information-val-required = " The State / Region field is required. " id = " Region " name = " SelectedRegionCode " > 56 < option value = " AL " > Alabama </ option > 57 < choice value = " AK " > Alaska </ option > 58 ... 59 < option value = " WY " > Wyoming </ option > 60 </ select > 61 < span class = " field-validation-valid text-danger " information-valmsg-for = " SelectedRegionCode " data-valmsg-replace = " true " > </ span > 62 </ div > 63 </ div > 64 < div form = " form-group " > 65 < div class = " col-physician-offset-2 col-doctor-10 " > 66 < input type = " submit " value = " Save " grade = " btn btn-primary " /> 67 </ div > 68 </ div > 69 </ div > 70 </ course > 71 </ div > 72 < div id = " SelectAddressTypePartial " > 73 < form activity = " /Customer/AddressTypePartial/68f8202d-21cb-4090-a86c-0722bf588d1b " data-ajax = " true " data-ajax-method = " Postal service " data-ajax-mode = " replace " data-ajax-update = " #CreateAddress " id = " form0 " method = " post " > 74 < input name = " __RequestVerificationToken " blazon = " hidden " value = " w6veexTOKQxJc3_3BQh7yRC7mHM-iSQgkXaIQdh3EZsTVELEnsxpgpYtSSpZ4CO0ZZdfQrEjck8UBomFrTcHfJuH343y1n1eWv_OmDCjAUE1 " /> 75 < div class = " form-horizontal " > 76 < 60 minutes /> 77 < h4 > Select an address type to add </ h4 > 78 < input data-val = " true " data-val-length = " The field CustomerID must be a cord with a maximum length of 38. " data-val-length-max = " 38 " id = " CustomerID " proper noun = " CustomerID " type = " subconscious " value = " 68f8202d-21cb-4090-a86c-0722bf588d1b " /> 79 < div course = " course-grouping " > fourscore < label class = " control-label col-md-2 " for = " SelectedAddressType " id = " AddressTypeLabel " > Address Type </ characterization > 81 < div class = " col-md-ten " > 82 < select class = " class-control " id = " AddressType " proper noun = " SelectedAddressType " > 83 < option value = " Email " > Email </ choice > 84 < pick value = " Postal " > Postal </ option > 85 </ select > 86 < span class = " field-validation-valid text-danger " data-valmsg-for = " SelectedAddressType " data-valmsg-supercede = " true " > </ bridge > 87 </ div > 88 </ div > 89 < div class = " form-group " > xc < div form = " col-md-offset-2 col-md-10 " > 91 < input type = " submit " value = " Select " class = " btn btn-primary " /> 92 </ div > 93 </ div > 94 </ div > 95 </ form > 96 </ div > 97 98 < div id = " CreateAddress " > </ div > 99 100 < div class = " row " > 101 < div class = " form-group " > 102 < div form = " col-doc-12 " > 103 < hr /> 104 < div > 105 < a href = " /Client " > Dorsum to List </ a > 106 </ div > 107 </ div > 108 </ div > 109 </ div > 110... 111 < script src = " /Scripts/jquery-3.ii.1.js " > </ script > 112 < script src = " /Scripts/bootstrap.js " > </ script > 113 < script src = " /Scripts/respond.js " > </ script > 114 < script src = " /Scripts/jquery.unobtrusive-ajax.js " > </ script > 115 < script src = " /Scripts/jquery.validate.js " > </ script > 116 < script src = " /Scripts/jquery.validate.unobtrusive.js " > </ script > 117... 118 </ body > 119 </ html >
html
Customer/Edit Ajax Response
When "Email" is selected for Address Type and the Select button is pressed, the CreateAddress
<div>
is replaced with the following code:
1 < div id = " CreateAddress " > ii < form action = " /Client/CreateEmailAddressPartial " method = " postal service " > < input name = " __RequestVerificationToken " type = " hidden " value = " p3BCpdqspecbfFOxrQfzdrt9cyoiVgtloMzHDYUbYgmeVbEssngLCmfWTUGGY0p8sWGzOFex1PURQDZCctvoteNvTBeDVfUgPJ8CrebXxl41 " /> < div course = " form-horizontal " > 3 < hour /> four < h4 > Add a new Electronic mail Address </ h4 > five < input data-val = " true " information-val-length = " The field CustomerID must be a string with a maximum length of 38. " data-val-length-max = " 38 " id = " CustomerID " proper name = " CustomerID " blazon = " hidden " value = " 68f8202d-21cb-4090-a86c-0722bf588d1b " /> 6 < div course = " class-group " > 7 < label class = " control-characterization col-md-2 " for = " Email " > Email </ label > 8 < div class = " col-md-10 " > 9 < input class = " form-control text-box single-line " id = " electronic mail " proper name = " Email " blazon = " electronic mail " value = " " /> 10 < span grade = " field-validation-valid text-danger " data-valmsg-for = " Email " data-valmsg-supercede = " truthful " > </ span > 11 </ div > 12 </ div > 13 < div class = " class-group " > xiv < div class = " col-doctor-showtime-2 col-md-10 " > xv < input id = " AddButton " type = " submit " value = " Add " class = " btn btn-primary " /> 16 </ div > 17 </ div > 18 </ div > 19 </ course > 20 </ div >
html
This adds a third <form>
element to the page with its own submit button. Selecting "Postal" in the Address Type drop-downwards and pressing Select adds the corresponding partial view for adding a postal address.
Each form interacts with its ain controller methods, every bit do the forms for editing customer information and selecting the type of address to add (due east-mail or postal). Accordingly, updated information about the customer can be added using the outset form on the page independent of the submission of the e-mail address or postal address information.
Controller Actions
Looking at the CustomerController.cs
methods will provide a more than complete understanding of how each section of of the Customer/Edit view works and how Ajax is used to update the view with new content without refreshing the entire page.
The following tabular array summarizes the elements of the view and the controller methods with which they interact:
View | ViewModel | Course Helper Type | HTTP Action | Controller Method |
---|---|---|---|---|
Edit.cshtml | (none) | (none) | Get | ActionResult Edit(cord id) |
EditCustomerPartial.cshtml | CustomerEditViewModel.cs | HTML | GET | ActionResult EditCustomerPartial(string id) |
EditCustomerPartial.cshtml | CustomerEditViewModel.cs | HTML | Mail service | ActionResult EditCustomerPartial(CustomerEditViewModel model) |
AddressTypePartial.cshtml | AddressTypeViewModel.cs | Ajax | GET | ActionResult AddressTypePartial(cord id) |
AddressTypePartial.cshtml | AddressTypeViewModel.cs | Ajax | Post | ActionResult AddressTypePartial(AddressTypeViewModel model) |
CreateEmailAddressPartial.cshtml | EmailAddressViewModel.cs | HTML | Postal service | ActionResult CreateEmailAddressPartial(EmailAddressViewModel model) |
CreatePostalAddressPartial.cshtml | PostalAddressEditViewModel.cs | HTML | POST | ActionResult CreateEmailAddressPartial(PostalAddressEditViewModel model) |
Note that in that location is no POST method for the Edit parent view because all the forms and submit buttons belong to partial views and each has its own associated controller methods.
Note also that there are no HTTP GET deportment for the e-mail accost and postal accost partial views. These views are rendered by the POST action signature of the AddresTypePartial
method.
Edit View Get Method
Rendering the view begins with an ActionResult
method for Edit.cshtml, the parent page. Note that there is no view model associated with this view; as described above, all the related view models are associated with the partial views. All that this view needs to to is check for a valid GUID and return the view.
one // Get: Customer/Edit/68f8202d-21cb-4090-a86c-0722bf588d1b 2 public ActionResult Edit ( string id ) 3 { 4 if ( ! String . IsNullOrWhiteSpace ( id ) ) 5 { 6 bool isGuid = Guid . TryParse ( id , out Guid customerId ) ; 7 if ( isGuid && customerId != Guid . Empty ) eight { nine return View ( ) ; ten } xi } 12 render new HttpStatusCodeResult ( HttpStatusCode . BadRequest ) ; 13 }
csharp
EditCustomerPartial Go Method
This method is chosen during the rendering of Edit.cshtml by this line in the Razor view:
@Html.Action("EditCustomerPartial", new { id = Url.RequestContext.RouteData.Values["id"] })
Notation that the Html.Activeness
helper method passes the road value for the CustomerID
equally an argument. The value of id
is used to retrieve the customer record from the SQL Server database using the GetCustomer
method of CustomersRepository
.
The customer information is returned in an instance of CustomerEditViewModel
, which provides the values for the drop-downwards lists for Country
and Region
likewise as the electric current values for the country and region associated with the client record. This is all handled by the repository and so the business concern logic doesn't have to exist concerned with the data needed for mechanizing the user interface.
csharp ChildActionOnly public ActionResult EditCustomerPartial(string id) { if (!Cord.IsNullOrWhiteSpace(id)) { bool isGuid = Guid.TryParse(id, out Guid customerId); if (isGuid && customerId != Guid.Empty) { var repo = new CustomersRepository(); var model = repo.GetCustomer(customerId); return View(model); } } return new HttpStatusCodeResult(HttpStatusCode.BadRequest); }
1 The method is busy with the `ChildActionOnly` attribute to indicate that information technology tin only be called within a parent view, never as a standalone GET action. This prevents the partial view from being rendered on its ain and potentially existence used to subvert the proper functioning of the application. 2 3#### AddressTypePartial GET Method iv 5This method is called during the rendering of **Edit.cshtml** by this line in the Razor view: 6 7`@Html.Activity("AddressTypePartial", new { id = Url.RequestContext.RouteData.Values["id"] })` 8 nineAs with the fractional view for editing customer information, this GET method populates the information in the view model that supports the user interface. ten 11```csharp 12[ChildActionOnly] 13public ActionResult AddressTypePartial(string id) 14{ fifteen if (!Cord.IsNullOrWhiteSpace(id)) 16 { 17 bool isGuid = Guid.TryParse(id, out Guid customerId); xviii if (isGuid && customerId != Guid.Empty) 19 { 20 var repo = new MetadataRepository(); 21 var model = new AddressTypeViewModel() 22 { 23 CustomerID = id, 24 AddressTypes = repo.GetAddressTypes() 25 }; 26 return PartialView("AddressTypePartial", model); 27 } 28 } 29 return new HttpStatusCodeResult(HttpStatusCode.BadRequest); xxx}
At this betoken, the Razor engine has all the data and markup information technology needs to render the page. The Customer/Edit view can exist used by the user.
AddressTypePartial Mail service Method
When the user selects an address blazon to add together and presses the Select button, the data is sent to the server and handled past the POST method for AddressTypePartial
. This method will not execute unless the anti-forgery token associated with the class is valid.
i [ HttpPost ] two [ ValidateAntiForgeryToken ] iii public ActionResult AddressTypePartial ( AddressTypeViewModel model ) 4 { 5 if ( ModelState . IsValid && ! Cord . IsNullOrWhiteSpace ( model . CustomerID ) ) vi { 7 switch ( model . SelectedAddressType ) 8 { 9 instance "Electronic mail" : 10 var emailAddressModel = new EmailAddressViewModel ( ) 11 { 12 CustomerID = model . CustomerID 13 } ; 14 return PartialView ( "CreateEmailAddressPartial" , emailAddressModel ) ; fifteen case "Postal" : 16 var postalAddressModel = new PostalAddressEditViewModel ( ) 17 { 18 CustomerID = model . CustomerID nineteen } ; 20 var countriesRepo = new CountriesRepository ( ) ; 21 postalAddressModel . Countries = countriesRepo . GetCountries ( ) ; 22 var regionsRepo = new RegionsRepository ( ) ; 23 postalAddressModel . Regions = regionsRepo . GetRegions ( ) ; 24 return PartialView ( "CreatePostalAddressPartial" , postalAddressModel ) ; 25 default : 26 return new HttpStatusCodeResult ( HttpStatusCode . BadRequest ) ; 27 } 28 } 29 return new HttpStatusCodeResult ( HttpStatusCode . BadRequest ) ; thirty }
csharp
Depending on the blazon of address selected by the user, this method creates an instance of the appropriate view model and sets the value of CustomerID
. If the postal address type is selected, the controller besides populates the relevant SelectList
collections for the lists of countries and regions. The controller then returns the appropriate view along with the associated view model.
On the client side, the browser takes the HTML and data from the server and, using the JavaScript libraries, renders the partial view and its view model data in place of the <div id="CreateAddress">
chemical element.
At this point, the user can enter and submit information for the selected accost type, or re-select the address type and meet the page updated with the other fractional view. Once the user enters data and presses the Save push, the appropriate POST controller method handles the request.
CreateEmailAddressPartial POST Method
In the example of an e-mail accost, the Mail service method looks like this. It is a simple affair of using the repository to save the information and responding accordingly to the results of that method call.
1 [ HttpPost ] 2 [ ValidateAntiForgeryToken ] 3 public ActionResult CreateEmailAddressPartial ( EmailAddressViewModel model ) iv { five if ( ModelState . IsValid ) half-dozen { 7 var repo = new CustomersRepository ( ) ; 8 bool saved = repo . SaveEmailAddress ( model ) ; 9 if ( saved ) x { 11 return RedirectToAction ( "Edit" , new { id = model . CustomerID } ) ; 12 } thirteen } 14 return new HttpStatusCodeResult ( HttpStatusCode . BadRequest ) ; fifteen }
csharp
In the instance project, when the e-mail service address is successfully saved, the controller passes command to the method to load the Customer/Edit folio ( Edit.cshtml
) for the current customer. This is equivalent to resetting the folio. In real-world applications, any number of other results are possible, including reloading an Ajax partial view that displays the electric current listing of addresses of the associated type.
Other Ajax Actions
In addition to adding a new class to a page, the Ajax.BeginForm helper can be used to create Ajax functionality to perform other useful actions. The actionName
, controllerName
, and routeValues
parameters tin can be used to access controller deportment from a specific controller and pass a variety of data to the controller.
In improver, the AjaxOptions
parameter tin be used to define what happens with the fractional view as it is being added to the page. Some of the options are:
InsertionMode
- defines whether the new <form>
element replaces the identified element or is added before or after the existing element. This is useful when building a listing of items on the page as the user adds information.
OnBegin
- tin can set the JavaScript function to phone call before the <form>
element is added.
OnSuccess
- can set the JavaScript office to call when the <form>
has finished loading.
Determination
ASP.Cyberspace MVC AjaxHelper methods provide a flexible way to add together Ajax functionality to Razor views. In many cases this tin can provide the desired functionality without the resource commitment and potential learning curve associated with implementing a client-side framework like Angular.
Ajax helper methods leverage the developer's knowledge of server-side programming with C# and with the MVC design blueprint. They require minimal lawmaking in the Razor view and allow for powerful combinations of partial views, controller actions, and client-side JavaScript to create an interactive unmarried folio experience for the user.
Implementing the Model View ViewModel (MVVM) design pattern by combining Ajax helpers with partial views and associated view models can provide an effective separation of concerns for interactive pages built with these resource. Compatibility of ASP.Cyberspace security tools like the anti=forgery token with Ajax helpers ensures the robust security of ASP.Cyberspace without additional programming effort.
Developers should evaluate the capabilities of AjaxHelper methods before deciding to move from ASP.NET MVC to WebAPI and Angular (or another client-side framework). This is peculiarly true when search engine optimization (SEO) and page analytics integration are objectives.
More than Data
If y'all want to dive deeper into the topics discussed in this guide or experiment with the code shown above, the following is a selected list of resources.
Instance Project
The complete Visual Studio solution described in this guide is available on GitHub: BlipAjax
The instance projection is provided as is, without any warranty expressed or implied. Neither Pluralsight nor the author is responsible for any errors or omissions.
Related Pluralsight Courses
ASP.NET MVC Advanced Topics past Scott Allen, 22 July 2009. The get-go module of this grade, Ajax with ASP.Cyberspace MVC, provides a dainty narrated overview of the related technology.
Other Resources
Disclaimer: Pluraldight and the author of this guide are not responsible for the content, accuracy, or availability of third party resources.
Microsoft: System.Web.Mvc.Ajax namespace - This is the approved documentation for the AjaxExtensions (including the BeginForm method) and AjaxOptions classes. Notation that if y'all get looking for data on docs.microsoft.com it will kicking you lot over to this URL. Although this page refers to Visual Studio 2013, it is, in fact, the most recent documentation.
Wikipedia: Ajax (programming) - A prissy summary of the Ajax compages, history, and implementation. Good background for beginners looking for a fundamental grounding in the engineering.
Source: https://www.pluralsight.com/guides/asp-net-mvc-using-ajax-helpers-with-razor-partial-views
0 Response to "Ajax Img Upload Parameter Is Invalid Asp Net Mvc"
Post a Comment