0

I have this action:

[HttpPost]
public ActionResult Test(Test test) 
{
    ...
}

With this class:

public class Test
{
    public string txtTest { get; set; }
}

An html form has a text field named txtTest, and I can successfully call into my action above. What property name would allow me to do this:

public class Test
{
    [SomeAttribute(Name = "txtTest")]
    public string MyTest { get; set; }
}
5
  • 1
    could you elaborate some more? Commented Nov 8, 2012 at 18:12
  • Currently I am forced to match the name of my C# class's variable with the form field's name. I cannot change the name of the form field. Commented Nov 8, 2012 at 18:14
  • If you change the name of the form field, it will not be mapped back correctly to your class. If you want to do custom fields, you'll also have to write a custom ModelBinder. This SMELLS of an XY Question, because you have some solution but you aren't telling us what problem it is solving. Commented Nov 8, 2012 at 18:22
  • Another way to say my question is "What attribute on a class property will allow me to name that property as I see fit while still allowing MVC to correctly create instances of those classes in a controller action". I don't believe that this is an XY question. Commented Nov 8, 2012 at 19:01
  • @user961969. Didn't my answer help you? Commented Nov 9, 2012 at 3:08

2 Answers 2

2

Use ViewModel, don't use classes which are being used for something else.
Create ViewModel, for this specific View only.

one of the benefits is you don't need to change the names of properties the existing classes have.

You can use automapper which is highly used in MVC applications to map from the ViewModel to the Entity.

A good reading resource can be found here

Sign up to request clarification or add additional context in comments.

2 Comments

Perhaps I am misunderstanding you - I am not calling View() at all. I am simply trying to receive form data.
@user961969, so get that data with the viewmodel in the POST action. you can use AutoMapper to map from the DTO to the CTO.
1

Use the Display DataAnnotation

http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.aspx

6 Comments

I'm not sure it has anything to do with his question.
I tried this to no avail: [DisplayAttribute(Name = "txtTest")] public string MyTest { get; set; }
Do you have a reference to System.ComponentModel.DataAnnotations ?
Yes.The code compiled correctly, but the value from the form field was not present in the C# object.
Can you post the internals of your action and also your view code thanks.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.