0

I have ViewModel, View which uses this viewmodel and controller

in view I have input fields like this:

@Html.EditorFor(model => model.TransitApplication.ApplicationDate)

and field name is TransitApplication_ApplicationDate

I want to update some data from view in database but there is one problem

controller update source

 public ActionResult Update(int id, FormCollection collection)
    {

        string prefix = "TransitApplication";

        TransitApplication transitApplication = transitApplicationRepozitory.GetById(id);

        if (transitApplication == null)
            return Content("Error! Not Found!");

        if (TryUpdateModel(transitApplication, prefix))
        {
            if (ModelState.IsValid)
            {
               transitApplicationRepozitory.Update(transitApplication);
               transitApplicationRepozitory.Save();
               return RedirectToAction("Index");
            }
        }

        return Content("Error!");
    }

I want to take prefix (TransitApplication) name programmatically and not like I have string prefix = "TransitApplication";

some advice?

Irakli
  • 37
  • 1
  • 6

1 Answers1

0

Seeing that the form prefix is built using the Class Name of the Model property, what about:

if (TryUpdateModel(transitApplication, typeof(TransitApplication).Name))

This removes your magic string - although this isn't actually the property name on the model class, but I'm guessing that if you renamed class, you'd probably want to rename the referenced property on the model too - although it is a little brittle.

The alternative is you could use something like this GetPropertyInfo method which would allow you to get the property name as a string like this var propertyInfo = GetPropertyInfo(yourModelObject, u => u.UserID); - although you don't currently have an instantiated model class in your action atm.

Community
  • 1
  • 1
Tr1stan
  • 2,755
  • 1
  • 26
  • 45