How to pass Membership object as a model to view? - asp.net-mvc

I am trying to get all of the information for the user into a view with a form to edit the user's information. I have this controller action:
'
' GET: /Account/EditRegistry/5
Public Function EditRegistry(Optional id As String = Nothing) As ActionResult
' get user model
Dim model = Membership.GetUser(id)
' pass username to view
ViewData("UserName") = id
Return View(model)
End Function
And, I am using this view:
#ModelType MyBlog.RegisterModel
#Code
ViewData("Title") = "Register"
End Code
<h2>Create a New Account</h2>
<p>
Use the form below to create a new account.
</p>
<p>
Passwords are required to be a minimum of #Membership.MinRequiredPasswordLength characters in length.
</p>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#Using Html.BeginForm()
#Html.ValidationSummary(True, "Account creation was unsuccessful. Please correct the errors and try again.")
#<div>
<fieldset>
<legend>Account Information</legend>
#Html.Hidden("m.UserName", ViewData("UserName"))
<div class="editor-label">
#Html.LabelFor(Function(m) m.Email)
</div>
<div class="editor-field">
#Html.TextBoxFor(Function(m) m.Email)
#Html.ValidationMessageFor(Function(m) m.Email)
</div>
<div class="editor-label">
#Html.LabelFor(Function(m) m.Password)
</div>
<div class="editor-field">
#Html.PasswordFor(Function(m) m.Password)
#Html.ValidationMessageFor(Function(m) m.Password)
</div>
<div class="editor-label">
#Html.LabelFor(Function(m) m.ConfirmPassword)
</div>
<div class="editor-field">
#Html.PasswordFor(Function(m) m.ConfirmPassword)
#Html.ValidationMessageFor(Function(m) m.ConfirmPassword)
</div>
<div class="editor-label">
#Html.LabelFor(Function(m) m.Company, "Companies")
</div>
<div class="editor-field">
#Html.DropDownList("Company", String.Empty)
#Html.ValidationMessageFor(Function(m) m.Company)
</div>
<div class="editor-label">
#Html.LabelFor(Function(m) m.IsCompanyOwner, "Company Owner?")
</div>
<div class="editor-field">
#Html.CheckBoxFor(Function(m) m.IsCompanyOwner)
#Html.ValidationMessageFor(Function(m) m.IsCompanyOwner)
</div>
<div class="editor-label">
#Html.LabelFor(Function(m) m.Blog, "Blogs")
</div>
<div class="editor-field">
#Html.DropDownList("Blog", String.Empty)
#Html.ValidationMessageFor(Function(m) m.Blog)
</div>
<div class="editor-label">
#Html.LabelFor(Function(m) m.IsBlogOwner, "Blog Owner?")
</div>
<div class="editor-field">
#Html.CheckBoxFor(Function(m) m.IsBlogOwner)
#Html.ValidationMessageFor(Function(m) m.IsBlogOwner)
</div>
<p>
<input type="submit" value="Register" />
</p>
</fieldset>
</div>
End Using
The error I get is:
The model item passed into the dictionary is of type
'System.Web.Security.MembershipUser', but this dictionary requires a
model item of type 'MyBlog.RegisterModel'.
How can I resolve this error and get the user's info into the model and into the form in the view?

The error message is pretty self explanatory. Your view is strongly typed to MyBlog.RegisterModel but you are passing MembershipUser which is what the Membership.GetUser method returns. So go ahead and pass the correct model type to your view:
Public Function EditRegistry(Optional id As String = Nothing) As ActionResult
' get user model
Dim model = Membership.GetUser(id)
' build a view model
Dim viewModel = New RegisterModel()
viewModel.Email = model.Email
' pass username to view
ViewData("UserName") = id
Return View(viewModel)
End Function

Related

Parameter for "Delete" post method has blank attributes in ASP.NET MVC

I'm having an issue in my MVC application (for making basic CRUD changes to a database) where the object parameter getting passed to my "Delete" post method has blank parameters, even though the object returned by the get method is correct. As a result, when I try to delete the object from the database I get the following exception:
A first chance exception of type 'System.ArgumentNullException' occurred in EntityFramework.dll
System.ArgumentNullException: Value cannot be null.
Parameter name: entity
at System.Data.Entity.ModelConfiguration.Utilities.RuntimeFailureMethods.Requires(Boolean condition, String userMessage, String conditionText)
at System.Data.Entity.DbSet`1.Remove(TEntity entity)
at MvcApplication1.HomeController.Delete(ISBN bookToDelete) in C:\Users\MMcCrimmon\Documents\Visual Studio 2012\Projects\MortonPublishingDatabaseInterface\MvcApplication1\Controllers\HomeController.vb:line 103
After a bit of digging I found this question: Missing something in "Delete" post method in MVC (EF 4.1), which seems to be identical, but the answers there did not resolve my problem. What am I doing wrong here?
Here's my controller code:
' GET: /Home/Delete/5
Function Delete(ByVal id As String) As ActionResult
Dim bookToDelete = _db.ISBNs.Find(id)
Return View(bookToDelete)
End Function
' POST: /Home/Delete/5
<HttpPost()> _
Function Delete(bookToDelete As ISBN) As ActionResult
Dim originalBook = _db.ISBNs.Find(bookToDelete.Product_Code)
Try
_db.ISBNs.Remove(originalBook)
_db.SaveChanges()
Return RedirectToAction("Index")
Catch exc As Exception
Return View(originalBook)
End Try
End Function
and here's the view for the Delete page:
#ModelType MvcApplication1.ISBN
#Code
ViewData("Title") = "Delete"
Layout = "~/Views/Shared/_Layout.vbhtml"
End Code
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<p/>
<fieldset>
<legend>ISBN</legend>
<div class="display-label">
<strong>#Html.DisplayNameFor(Function(model) model.Product_Code)</strong>
</div>
<div class="display-field">
#Html.DisplayFor(Function(model) model.Product_Code)
</div>
<div class="display-label">
<strong>#Html.DisplayNameFor(Function(model) model.Title)</strong>
</div>
<div class="display-field">
#Html.DisplayFor(Function(model) model.Title)
</div>
<div class="display-label">
<strong>#Html.DisplayNameFor(Function(model) model.ISBN_UPC)</strong>
</div>
<div class="display-field">
#Html.DisplayFor(Function(model) model.ISBN_UPC)
</div>
<div class="display-label">
<strong>#Html.DisplayNameFor(Function(model) model.ManualName)</strong>
</div>
<div class="display-field">
#Html.DisplayFor(Function(model) model.ManualName)
</div>
<div class="display-label">
<strong>#Html.DisplayNameFor(Function(model) model.PgCount)</strong>
</div>
<div class="display-field">
#Html.DisplayFor(Function(model) model.PgCount)
</div>
<div class="display-label">
<strong>#Html.DisplayNameFor(Function(model) model.BookSize)</strong>
</div>
<div class="display-field">
#Html.DisplayFor(Function(model) model.BookSize)
</div>
<div class="display-label">
<strong>#Html.DisplayNameFor(Function(model) model.ColorOrBW)</strong>
</div>
<div class="display-field">
#Html.DisplayFor(Function(model) model.ColorOrBW)
</div>
<div class="display-label">
<strong>#Html.DisplayNameFor(Function(model) model.PageCount)</strong>
</div>
<div class="display-field">
#Html.DisplayFor(Function(model) model.PageCount)
</div>
</fieldset>
#Using Html.BeginForm()
#Html.AntiForgeryToken()
#<p>
<input type="submit" value="Delete" /> |
#Html.ActionLink("Back to List", "Index")
</p>
End Using
Following the answer for Missing something in "Delete" post method in MVC (EF 4.1), here's the modified view (still doesn't work):
#ModelType MvcApplication1.ISBN
#Code
ViewData("Title") = "Delete"
Layout = "~/Views/Shared/_Layout.vbhtml"
End Code
<h2>Delete</h2>
<h3>Are you sure you want to delete this?</h3>
<p/>
#Using Html.BeginForm()
#Html.AntiForgeryToken()
#<fieldset>
<legend>ISBN</legend>
<div class="display-label">
<strong>#Html.DisplayNameFor(Function(model) model.Product_Code)</strong>
</div>
<div class="display-field">
#Html.DisplayFor(Function(model) model.Product_Code)
</div>
<div class="display-label">
<strong>#Html.DisplayNameFor(Function(model) model.Title)</strong>
</div>
<div class="display-field">
#Html.DisplayFor(Function(model) model.Title)
</div>
<div class="display-label">
<strong>#Html.DisplayNameFor(Function(model) model.ISBN_UPC)</strong>
</div>
<div class="display-field">
#Html.DisplayFor(Function(model) model.ISBN_UPC)
</div>
<div class="display-label">
<strong>#Html.DisplayNameFor(Function(model) model.ManualName)</strong>
</div>
<div class="display-field">
#Html.DisplayFor(Function(model) model.ManualName)
</div>
<div class="display-label">
<strong>#Html.DisplayNameFor(Function(model) model.PgCount)</strong>
</div>
<div class="display-field">
#Html.DisplayFor(Function(model) model.PgCount)
</div>
<div class="display-label">
<strong>#Html.DisplayNameFor(Function(model) model.BookSize)</strong>
</div>
<div class="display-field">
#Html.DisplayFor(Function(model) model.BookSize)
</div>
<div class="display-label">
<strong>#Html.DisplayNameFor(Function(model) model.ColorOrBW)</strong>
</div>
<div class="display-field">
#Html.DisplayFor(Function(model) model.ColorOrBW)
</div>
<div class="display-label">
<strong>#Html.DisplayNameFor(Function(model) model.PageCount)</strong>
</div>
<div class="display-field">
#Html.DisplayFor(Function(model) model.PageCount)
</div>
</fieldset>
#<p>
<input type="submit" value="Delete" /> |
#Html.ActionLink("Back to List", "Index")
</p>
End Using
Full disclosure: I'm new to MVC, ASP, and VB.NET, so please forgive me if I'm making some rookie mistake here...
You don't seem to be passing the "bookToDelete" parameter through to the DELETE method. In fact you shouldn't be passing this through as it's an object not a simple value. I would pass the "book id" through on delete post action (same as delete get action)
Altering the delete view form code by adding the following line between the #Using Html.BeginForm() and End Using lines
#Html.HiddenFor(model => model.id)
And change the DELETE post method in your controller to
Function Delete(id as string) As ActionResult
Dim originalBook = _db.ISBNs.Find(id)
You need to add a to your form indicating the parameter to pass to your controller.
E.g. If your controller is using "BookToDeleteID" as parameter name, your view html should look like this:
<form>
......
<input type="hidden" name="BookToDeleteID" value="A_NUMBER"/>
<input type="submit" value="delete"/>
</form>
Sometimes it has weird cases where you have to pass JSON objects to controllers. Maybe it's a data integrity concern by Microsoft. So I guess you have to parse the entire model for all actions.

How to get a form value in another form value submission

I had username and password in first form and retrieve password in another form , in which i want userame entered in first form in submission of second form.
#model Network.Models.LoginDetail
<script type="text/javascript">
</script>
#{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<p>
Please enter your user name and password. #Html.ActionLink("Register", "Register") if you don't have an account.
</p>
#using (Html.BeginForm("Index","Student",FormMethod.Post)) {
<div>
<fieldset>
<legend>Account Information</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Username)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Username)
#Html.ValidationMessageFor(model => model.Username)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Password)
#Html.ValidationMessageFor(model => model.Password)
</div>
<p>
<input type="submit" value="Log in" style="width: 200px"/>
</p>
#ViewBag.Message
</fieldset>
</div>
}
#using (Html.BeginForm("RetrievePassword","Student",FormMethod.Post)) {
<p>
Forgot password? <input type="submit" onclick="updateUsername();"value="Click Here" style="width: 150px"/> Entering your username to retrieve your password.
</p>
#Html.HiddenFor(model => model.Username)
}
How can we acheive this, i tried in javascript capturing of username in hiddenfield but not working.
Or can form within form be used to acheive this.
Please provide a solution.
Thanks,
Michaeld
At the post method of "Index" action in "Stundent" controller you will be able to get the value either in formcollection or in LoginDetail object form.
Example:
public ActionRestult Index(FormCollection FC)
{
string UserName = FC["Username"];
string Password = FC["Password"];
}
Or Alternatively
public ActionRestult Index(LoginDetail obj)
{
string UserName = obj.Username;
string Password = obj.Password;
}
This will fix your concern.

Adding model with user input and hard coded values

Okay so I am using the MVC framework. I have a view for adding a model. At the moment I am using the default "Create" controller.
I want to be able to create a model with my own variables pre-set. For example the model.UserId I want to set to the users Id. I want some values to be inputed by the user and I want some to be already set. Is there a way I could do something like this
(pseudo code)
model.matchId = 123
model.prediction type = "user input"
add model
here is my current code below
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Predictions</legend>
<div class="editor-label">
#Html.LabelFor(model => model.MatchId, "Match")
</div>
<div class="editor-field">
#Html.DropDownList("MatchId", String.Empty)
#Html.ValidationMessageFor(model => model.MatchId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.UserId, "User")
</div>
<div class="editor-field">
#Html.DropDownList("UserId", String.Empty)
#Html.ValidationMessageFor(model => model.UserId)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Type)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Type)
#Html.ValidationMessageFor(model => model.Type)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Prediction)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Prediction)
#Html.ValidationMessageFor(model => model.Prediction)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
In the controller, you would set the values on the model before returning it to the View.
public class HomeController : Controller
{
public ActionResult About()
{
var model = new MyModel();
model.SomeId = 123;
model.SomeOtherProperty = "Hello World";
return View(model);
}
}

I don't know how to useform action on view razor

I am trying to save values in salesforce on my form submit button .
I dont know how to use form action method in view razor with validation ....
Here is my code for salesforce which I need to implement on submit button of my form so that it make an entry in salesforce:
<form action="https://www.salesforce.com/servlet/..." method="POST" >
<input type=hidden name="oid" value="111">
<input type=hidden name="retURL" value = "http://test" />
here is my view page:
#model nd.Models.PopupDemoModel
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()){
#Html.ValidationSummary(true)
<fieldset>
<div class="editor-label grid_2">
#Html.LabelFor(model => model.first_name )
</div>
<div class="editor-field grid_3">
#Html.TextBoxFor(model => model.first_name , new { #class = "demo-field-longer" })
</div>
<div class="grid_3 error long" style="margin-left:250px">
#Html.ValidationMessageFor(model => model.first_name )
</div>
<div class="clear"></div>
<div class="editor-label grid_2">
#Html.LabelFor(model => model.email )
</div>
<div class="editor-field grid_3">
#Html.TextBoxFor(model => model.email , new { #class = "demo-field-longer" })
</div>
<div class="grid_3 error long" style="margin-left:250px">
#Html.ValidationMessageFor(model => model.email )
</div>
<div class="clear"></div>
<div class="editor-label grid_2">
#Html.LabelFor(model => model.phone )
</div>
<div class="editor-field grid_3">
#Html.TextBoxFor(model => model.phone , new {#class="demo-field-longer"})
</div>
<div class="grid_3 error long" style="margin-left:250px">
#Html.ValidationMessageFor(model => model.phone )
</div>
<div class="clear"></div>
<div class="editor-label grid_2">
#Html.LabelFor(model => model.company )
</div>
<div class="editor-field grid_3">
#Html.TextBoxFor(model => model.company , new { #class = "demo-field-longer" })
</div>
<div class="grid_3 error long" style="margin-left:250px">
#Html.ValidationMessageFor(model => model.company)
</div>
<div class="clear"></div>
<div class="clear"></div>
<div class="grid_2 sub-spacer"> </div>
<div class="editor-field grid_2 submit">
<input type="submit" value="Submit" id="demo-submit-button"/><br />
#ViewData["DemoMessage"]
</div>
</fieldset>
}
Any help is appreciated....
You can do this as below:
#using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { id = "cssClassorId" })) {
}

How can insert fix value in a field when creating a new row

I am working on asp.net mvc3. I have designed database in SQL Server. And I access database using ado.net, I am designing a "CREATE" page.
This is my view.cshtml
#model CalcoWOMS.Models.ProductFormulation
#{
ViewBag.Title = "doProductFormulation";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>ProductFormulation</legend>
<div>
#Html.EditorFor(model => model.ProductID) <!-- i want to insert fix value (100) in this ProductID field in ProductFormulation Table -->
#Html.ValidationMessageFor(model => model.ProductID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.RawMaterialID)
</div>
<div class="editor-field">
#Html.DropDownList("RawMaterialID","SELECT")
#Html.ValidationMessageFor(model => model.RawMaterialID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Code)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Code)
#Html.ValidationMessageFor(model => model.Code)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Description)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Description)
#Html.ValidationMessageFor(model => model.Description)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.MinimumBatchSize)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.MinimumBatchSize)
#Html.ValidationMessageFor(model => model.MinimumBatchSize)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Quantity)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Quantity)
#Html.ValidationMessageFor(model => model.Quantity)
</div>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "ProductFormulationIndex")
</div>
I want to insert fixed value (100) in this ProductID field in ProductFormulation table and don't want to create editable box. What should I
do for this ?
Perhaps I don't understand the question (I'm more of a backend developer), but it seems like the simple solution is remove these two lines:
<div>
#Html.EditorFor(model => model.ProductID)
#Html.ValidationMessageFor(model => model.ProductID)
</div>
Then update the Model in your controller's Create, [post] method to update the ProductID to 100, prior to writing it out to the repository. Of course, how you'd do that depends on your controller structure, which you haven't posted.
As I understand it, the alternative would be to have a hidden field on the page and create the Model with a ProductID of 100 in the initial Create call but if you're always going to hard code the product id (which to be honest seems questionable) to 100, then this seems pointless...

Resources