Custom update method in MVC 4 with WCF - asp.net-mvc

I am a newbie in MVC and currently using MVC 4 + EF Code First and WCF in my web project. Basically, in my project, WCF services will get the data from database for me, and it will take care of updating data as well. As a result, when I finish updating a record, I have to call the service client to make the change for me other than the "traditional" MVC way. Here is my sample code:
Model:
[DataContract]
public class Person
{
[Key]
[DataMember]
public int ID{ get; set; }
[DataMember]
public string Name{ get; set; }
[DataMember]
public string Gender{ get; set; }
[DataMember]
public DateTime Birthday{ get; set; }
}
Controller:
[HttpPost]
public ActionResult Detail(int ID, string name, string gender, DateTime birthday)
{
// get the WCF proxy
var personClient = personProxy.GetpersonSvcClient();
//update the info for a person based on ID, return true or false
var result = personClient.Updateperson(ID, name, gender, birthday);
if (result)
{
return RedirectToAction("Index");
}
else
{
//if failed, stay in the detail page of the person
return View();
}
}
View:
#model Domain.person
#{
ViewBag.Title = "Detail";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Detail</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Person</legend>
#Html.HiddenFor(model => model.ID)
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Gender)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Gender)
#Html.ValidationMessageFor(model => model.Gender)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Birthday)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Birthday)
#Html.ValidationMessageFor(model => model.Birthday)
</div>
<p>
<input type="submit" value="Update"/>
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
The controller is the part I am confused of. The Detail function takes multiple parameters, how can I call it from the View? Also, what should I put into this return field in the controller:
//if failed, stay in the detail page of the person
return View();
We usually put the model in, but the model seems to be not changed, since I am updating the database directly from my WCF service.
Any suggestion would be really appreciated!
UPDATE:
I know I can probably get it works by change the update method to take only one parameter which is the model itself, but this is not an option in my project.

you call the Details action in the controller when you hit "Update"
//sidenote : use single parameter in your function that accepts the values it makes life easier

The form will call the post method in the controller that has the same name as the get method that rendered the view when it is submitted.
You can alter this default behavior by specifying parameters in the BeginForm method
#using (Html.BeginForm("SomeAction", "SomeController"))
Also, you are using a strongly typed view (good!), so you can change the signature of your post method to accept the model object
[HttpPost]
public ActionResult Detail(Person person)

Related

ASP.Net MVC 4.0 - Validation Issues With array based properties on ViewModel

ASP.Net MVC 4.0 - Validation Issues With array based properties on ViewModel .
Scenario :
When a ViewModel has a string array as a property type,the default Scaffolding template for say, Edit, does not render the that property in the markup.
Say, I have ViewModel setup like this :
Employee.cs
public class Employee
{
[Required]
public int EmpID
{
get;
set;
}
[Required]
public string FirstName
{
get;
set;
}
[Required]
public string LastName
{
get;
set;
}
[Required]
public string[] Skills
{
get;
set;
}
}
}
The (strongly typed) Edit View generated by the scaffolding template, as shown below, typically skips the portion relevant to field Skills.
**Employee.cshtml**
#model StringArray.Models.Employee
#{
ViewBag.Title = "EditEmployee";
}
<h2>EditEmployee</h2>
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Employee</legend>
<div class="editor-label">
#Html.LabelFor(model => model.EmpID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.EmpID)
#Html.ValidationMessageFor(model => model.EmpID)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.FirstName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.FirstName)
#Html.ValidationMessageFor(model => model.FirstName)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.LastName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.LastName)
#Html.ValidationMessageFor(model => model.LastName)
</div>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
The corresponding Controller code is
..
[HttpGet]
public ActionResult EditEmployee()
{
Employee E = new Employee()
{
EmpID = 1,
FirstName = "Sandy",
LastName = "Peterson",
Skills = new string[] { "Technology", "Management", "Sports" }
};
return View(E);
}
[HttpPost]
public ActionResult EditEmployee(Employee E)
{
return View(E);
}
To get the missing section for the Skills field, I added
Snippet to the View
<div class="editor-label">
#Html.LabelFor(model => model.Skills)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Skills)
#Html.ValidationMessageFor(model => model.Skills)
</div>
Corresponding UIHint to the ViewModel
[UIHint("String[]")]
public string[] Skills ...
EditorTemplates inside relevant folder as
~\View\shared\EditorTemplates\String[].cshtml
and
~\View\shared\EditorTemplates\mystring.cshtml
string[].cshtml
#model System.String[]
#if(Model != null && Model.Any())
{
for (int i = 0; i < Model.Length; i++)
{
#Html.EditorFor(model => model[i], "mystring")
//Html.ValidationMessageFor(model => model[i])
}
}
mystring.cshtml
#model System.String
#{
//if(Model != null)
{
//To resolve issue/bug with extra dot getting rendered in the name - like
//Skills.[0], Skills.[1], etc.
//ViewData.TemplateInfo.HtmlFieldPrefix=ViewData.TemplateInfo.HtmlFieldPrefix.Replace(".[", "[");
#Html.TextBoxFor(model => model)
}
}
But despite this all, the Validations for the Skills section [with 3 fields/elements - refer the EditEmployee method in Controller above.]
are entirely skipped, on postback.
I tried below changes inside the mystring.cshtml EditorTemplate :
//to correct the rendered names in the browser from Skills.[0] to Skills for all the 3 items in the
//Skills (string array), so that model binding works correctly.
string x = ViewData.TemplateInfo.HtmlFieldPrefix;
x = x.Substring(0, x.LastIndexOf("."));
#Html.TextBoxFor(model =>model, new { Name = x })
Postback WORKS But Validations DON'T, since the "data-valmsg-for" still points to <span class="field-validation-valid" data-valmsg-for="Skills" data-valmsg-replace="true"></span>
and thus doesn't apply at granular level - string element level.
Lastly, I tried removing #Html.ValidationMessageFor(model => model.Skills) from the Employee.cshtml and correspondingly adding the
same to string[].cshtml as #Html.ValidationMessageFor(model => model[i]).
But this led to data-valmsg-for getting rendered for each granular string element like
data-valmsg-for="Skills.[0]" ,
data-valmsg-for="Skills.[1]" and data-valmsg-for="Skills.[2]", respectively.
Note: Validations work for other fields - EmpID, FirstName LastName, BUT NOT for Skills.
Question
How do I set the data-valmsg-for="Skills" for each of the above three granular elements related to Skills property.
I am stuck on this for quite some time now. It would be nice if some one can point out the issue, at the earliest.
Thanks, Sandesh L
This is where you like to change
[Required]
public string[] Skills
{
get;
set;
}
You are giving validation on the array.
you might want to have a new string class call Skill
[Required]
public string Skill
{
get;
set;
}
And you can change to you model with
[Required]
public List<Skill> Skills
{
get;
set;
}
I prefer using List instead of array. Then, you can change you skill view according to the model updated
you template view can be something like
#model IEnumerable<Skill>
<div class="editor-label">
<h3>#Html.LabelFor(model=> model.Skills)
</h3>
</div>
<div class="editor-field">
#foreach (var item in Model)
{ #Html.Label(model => item)
#Html.TextBoxFor(model => item) <br/>
}
#Html.ValidationMessageFor(model => item)

Can i have more than one Post method in asp.net mvc controller?

I have two views, one is CustomerDetail.cshtml and another is PAymentDetail.cshtml and i have one controller QuoteController.cs.
Both the Views has Submit buttons and HTTPPOST method for both the views are in QuoteController.cs.
[HttpPost]
public ActionResult CustomerDetail(FormCollection form)
{
}
[HttpPost]
public ActionResult PAymentDetail(FormCollection form)
{
}
Now, when i click on Submit button of Payment details, it is calling/routing to HttpPost method of CustomerDetail rather than PAymentDetail.
Could anyone help me on this?? What i'm doing wrong? Both The form method is POST.
For the PaymentDetail, you use this in the view:
#using(Html.BeginForm("PAymentDetail","Quote",FormMethod.Post))
{
//Form element here
}
The result html will be
<form action="/Quote/PAymentDetail" method="post"></form>
The same for customer Detail
#using(Html.BeginForm("CustomerDetail","Quote",FormMethod.Post))
{
//Form element here
}
Hope that help. Having two post methods in the same controller is not a problems, as long as these methods have different names.
For a better way other than FormCollection, I recommend this.
First, you create a model.
public class LoginModel
{
public string UserName { get; set; }
public string Password { get; set; }
public bool RememberMe { get; set; }
public string ReturnUrl { get; set; }
}
Then, in the view:
#model LoginModel
#using (Html.BeginForm()) {
<fieldset>
<div class="editor-label">
#Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.UserName)
//Insted of razor tag, you can create your own input, it must have the same name as the model property like below.
<input type="text" name="Username" id="Username"/>
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Password)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Password)
</div>
<div class="editor-label">
#Html.CheckBoxFor(m => m.RememberMe)
</div>
</fieldset>
}
These user input will be mapped into the controller.
[HttpPost]
public ActionResult Login(LoginModel model)
{
String username = model.Username;
//Other thing
}
Good luck with that.
Absolutely! Just ensure you are posting to the right action method, check your rendered HTML's form tags.
Also, the FormCollection isn't a good design for MVC.
If you want to have only one url, here is another approach: http://www.dotnetcurry.com/ShowArticle.aspx?ID=724
The idea is to use a form element (the button or a hidden element) to decide, which form has been submitted. Then you write a custom action selector (http://msdn.microsoft.com/en-us/library/system.web.mvc.actionmethodselectorattribute.aspx) which decides which action will be invoked.

How to turn off MVC form validation

I have a data-first set-up so my models are generated by the entity framework from my database and there is no default [Required] annotations. I have a simple table with three fields. One ID and two VARCHAR / text based fields.
No matter what I try, I cannot get the CRUD forms to stop validation. I disabled in the Web.config, I add [ValidateInput(false)] to the Create() method in the controller, but has no effect. I set the #Html.ValidationSummary to false,
This is the basic view:
#using (Html.BeginForm()) {
#Html.ValidationSummary(false)
<fieldset>
<legend>CallType</legend>
<div class="editor-label">
#Html.LabelFor(model => model.CALLTYPE)
</div>
<div class="editor-field">
#Html.TextBox("calltype", "", new { style = "width: 50px;" })
#Html.ValidationMessageFor(model => model.CALLTYPE)
</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>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
}
Model (generated by Framework):
public partial class CALLTYPES2
{
public int ID { get; set; }
public string CALLTYPE { get; set; }
public string DESCRIPTION { get; set; }
}
Even if I insert just one character in each field, it still says: "The Value 'x' is invalid"
(I leave the validation messages on so I can see what is going on.)
What am I supposed to do? And how would I validate these fields later on - can I just add [Required] to Model generated code? What if I regenerate the Model from the database?
Does this have something to do with the model state in the controller?
[HttpPost]
public ActionResult Create(CALLTYPES2 calltype)
{
if (ModelState.IsValid)
{
db.CALLTYPES2.Add(calltype);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(calltype);
}
Not sure what I am missing and the tutorials I have read do not shed much light. Thanks for your response and apologies for my ignorance.
UPDATE
Found my error - The object name "calltype" in the Method Create() is the same as the name/id of the form field "calltype". I guess the binder tries to bind the string "calltype" to the object "calltype". Renamed it to:
public ActionResult Create(CALLTYPES2 ctype)
Now it works in both the Edit and Create Windows. "ctype" is not clashing with "calltype".
You forgot to include the ID field in your form. You could include it as a hidden field:
#Html.HiddenFor(model => model.ID)
Now the value of the ID property will be sent to the server when the form is submitted and the default model binder should not complain.

MVC, passing values back from multiple partial views in a page

I have problem when I am trying to pass values back from my page which contains the same partial view twice.
My class definiton is like below:
public class Account : IEntity
{
public decimal CurrentBalance { get; set; }
public List<Person> AccountHolders { get; set; }
//to get round the non-existing enum support in EF4.3 wrap enum to int
public int StatusValue { get; set; }
public AccountStatus Status { get { return (AccountStatus)StatusValue; } set { StatusValue = (int) value; } }
public DateTime AccountOpenDate { get; set; }
public DateTime AccountCloseDate { get; set; }
public DateTime AccountSuspensionDate { get; set; }
}
It has a List of Person , which I made a partial view for (for a single one).
<fieldset>
<legend>Person</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Age)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Age)
#Html.ValidationMessageFor(model => model.Age)
</div>
</fieldset>
In the Create page for the Account I include 2 of the partial views I created as below.
<div id="Person1">
#Html.Partial("_CreateAccountHolder" )
</div>
<div id="Person2">
#Html.Partial("_CreateAccountHolder")
</div>
When I look at what is posted back, it contains the values (Name and Age as the properties of Person) I put in the form values of the page and I have have the tow of them as expected:
CurrentBalance=19&Status=Closed&AccountOpenDate=12%2F12%2F2012&Name=mustafa&Age=20&Name=sofia&Age=20&AccountCloseDate=12%2F12%2F2012&AccountSuspensionDate=12%2F12%2F2012
But when I look at my create method on my controller I see the AccountHolder list as null. I tried with various signatures...
public ActionResult Create(Account personalaccount, Person [] accountHolders)
public ActionResult Create(Account personalaccount, List accountHolders)
If I only have one partial view of Person and have my controller like this, I can see the Person object bound correctly.
public ActionResult Create(Account personalaccount, Person accountHolder)
Any ideas as to where I am going wrong?
If I understand your scenario correctly one way to accomplish this is to use Editor Templates instead of partial views. I have a little write up about them here:
codenodes.wordpress.com - MVC3 Editor Templates
To create an Editor Template:
if you don't already have a folder called "EditorTemplates" in the web project of your solution then create one in the Views\Shared folder.
add a new partial view and name it the same as the model you're rendering, in your case Person, so you would call it Person.cshtml (I know partial views are supposed to start with an underscore "_" but for an Editor Template it needs to be named the same as the model).
paste the code from your "_CreateAccountHolder" partial view into the new Person.cshtml Editor Template.
in your Create page render your AccountHolders list thusly:
<div id="People">
#Html.EditorFor(x => x.AccountHolders)
</div>
If you need to have individual divs around each Person then you can add these to your Editor Template. The good thing about Editor Templates is that you only need a single call to the template even if you have multiple Person objects in your list - no need to loop or anything like that as the template automatically renders each Person object. It also names the field correctly so it should post back something like this if for example you have 2 Person objects in your collection:
AccountHolders[0].Name
AccountHolders[0].Age
AccountHolders[1].Name
AccountHolders[1].Age
Here's the code for your Editor Template:
#model Person
<fieldset>
<legend>Person</legend>
<div class="editor-label">
#Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Name)
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
#Html.LabelFor(model => model.Age)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.Age)
#Html.ValidationMessageFor(model => model.Age)
</div>
</fieldset>
I understood my problem after reading
[http://stackoverflow.com/questions/653514/asp-net-mvc-model-binding-an-ilist-parameter][1]
Putting 2 partial views of the same type made the view return Name and Age pair with nothing to distingusih between the first and the second pair. I changed the parial view as below, but dont really like it...
<div class="editor-field">
#Html.TextBox("person[0].Name", "")
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-field">
#Html.TextBox("person[0].Age", "")
#Html.ValidationMessageFor(model => model.Age)
</div>
<div class="editor-field">
#Html.TextBox("person[1].Name", "")
#Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-field">
#Html.TextBox("person[1].Age", "")
#Html.ValidationMessageFor(model => model.Age)
</div>
It now postbacks something like below and I can read the IList in my controller..
CurrentBalance=19&Status=Closed&AccountOpenDate=12%2F12%2F2012&person%5B0%5D.Name=mustafa&person%5B0%5D.Age=19&person%5B1%5D.Name=sofia&person%5B1%5D.Age=20&AccountCloseDate=10%2F10%2F2012&AccountSuspensionDate=12%2F12%2F2012
First you should create CreateAccountModel with two instances of AccountModel, something like:
public class CreateAccountModel
{
public Account Person1 { get; set; }
public Account Person2 { get; set; }
}
Next, when you add your partial views, you should pass individual models to them, e.g:
<div id="Person1">
#Html.Partial("_CreateAccountHolder", Model.Person1)
</div>
<div id="Person2">
#Html.Partial("_CreateAccountHolder", Model.Person2)
</div>
Now MVC will automatically prefix all account fields with PersonX, so all fields will be unique.
Alternatively you can specify prefixes manually when you add your partial views:
{
var prefixData = new ViewDataDictionary { TemplateInfo = { HtmlFieldPrefix = "Person1" } };
Html.RenderPartial("_CreateAccountHolder", new ViewDataDictionary(prefixData));
}

asp.net mvc scaffolding and GUID as the primary key

I have a table with the following structure
GUID uniqueidentifier with default value newid(), and set as primary key
ID int
Description varchar(max)
I created an Entity Model using visual studio, and generated the views for editing/deleting etc (mvc scaffolding)
The problem is with "Editing", when I click that link, the appropriate form is showed with the correct data, but the "save" button doesn't work at all. Please note that other links (delete,create,details) work perfectly..
So, when I click the "Edit" link, the url is
http://localhost:10871/admin/Edit/e7d0c5ee-7782-411f-920e-7b0d93c924e1
and the form is displayed correctly, but the save button doesn't work, no network activity happens. Is something particular about using uniqueidentifers as primary key?
Thanks
---Code---
Edit.cshtml
#using (Html.BeginForm()) {
#Html.ValidationSummary(true)
<fieldset>
<legend>Domain</legend>
#Html.HiddenFor(model => model.GUID)
#Html.HiddenFor(model => model.ID)
<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>
<p>
<input type="submit" value="Save" />
</p>
</fieldset>
}
<div>
#Html.ActionLink("Back to List", "Index")
</div>
--AdminController.cs--
// GET: /Admin/Edit/5
public ActionResult Edit(Guid id)
{
Domain domain = db.Domains.Single(d => d.GUID == id);
return View(domain);
}
//
// POST: /Admin/Edit/5
[HttpPost]
public ActionResult Edit(Domain domain)
{
if (ModelState.IsValid)
{
db.Domains.Attach(domain);
db.ObjectStateManager.ChangeObjectState(domain, EntityState.Modified);
db.SaveChanges();
return RedirectToAction("Index");
}
return View(domain);
}
Edit2
In response to a comment by ZippyV, I added the following code in Edit.cshtml
<div class="editor-label">
#Html.LabelFor(model => model.ID)
</div>
<div class="editor-field">
#Html.EditorFor(model => model.ID)
#Html.ValidationMessageFor(model => model.ID)
</div>
to my surprise (or ignorance) - the GUID is being shown instead of ID
and apart from that - when I enter a value in that field (1,2 or any integer), I still get the message "The field ID must be a number."
The problem comes from the fact that you have a property called ID on your view model:
public class Domain
{
public int ID { get; set; }
...
}
and at the same time you have a route parameter called id in your Edit controller action:
public ActionResult Edit(Guid id)
{
...
}
Now here's what happens: The Html helpers (such as TextBoxFor, HiddenFor, ...) always first looks in the model state when binding a value (i.e. query string parameters, route values) and only at the end it looks at the value in the model. That's how all Html helpers work and it is by design.
So you have the following:
#Html.HiddenFor(model => model.ID)
The ID is taken NOT from the model but from your Route data (which is a Guid as specified in your action parameter). That's why it is very dangerous to use properties in the view model and action parameters that have the same name.
One possible workaround would be to rename your action parameter to something else:
public ActionResult Edit(Guid domainId)
{
Domain domain = db.Domains.Single(d => d.GUID == domainId);
return View(domain);
}
Of course now your routes might need to be adapted or use query string parameters: controller/edit?domainId=d578b4b7-48ec-4846-8a49-2120c17b6441 to invoke the Edit action.

Resources