On the property of the split Entity Data Model, the Data Annotations [Required] attribute is required.

asp.net-mvc c# data-annotations entity-framework

Question

My entity data model is divided using the Entity Framework's Splitting tables feature as follows:

+--------+    +--------------+
|  News  |    |  NewsImages  |
+--------+    +--------------+
| NewsID |    | NewsID       |
| Text   |    | Image        |
+--------+    +--------------+

Each News entity includes a navigation property with the nameNewsImage to cite the associated picture.


Zzz-27-Zzz is what I'm utilizing to verify my Model. I used the[Required] the characteristic onText possession of theNews class:

[MetadataType(typeof(NewsValidation))]
public partial class News
{
    /* ... */
}

public class NewsValidation
{
    [Required]
    public string Text { get; set; }
}

The server-side code I use to get the picture data is shown below:

[HttpPost]
public ActionResult Create(News news)
{
    if (ModelState.IsValid)
    {
        UpdateNewsImage(news);
        _newsRepository.Add(news);
        _newsRepository.SaveChanges();

        return RedirectToAction("Index");
    }
}

private void UpdateNewsImage(News news)
{
    byte[] newsImage = GetNewsImage();
    news.NewsImage = new NewsImage { Image = newsImage };
}

private byte[] GetNewsImage()
{
    foreach (string upload in Request.Files)
    {
        HttpPostedFileBase uploadedFile = Request.Files[upload];

        if (!uploadedFile.HasFile())
        {
            break;
        }

        Stream fileStream = uploadedFile.InputStream;
        int fileLength = uploadedFile.ContentLength;
        byte[] fileData = new byte[fileLength];
        fileStream.Read(fileData, 0, fileLength);

        return fileData;
    }

    return null;
}

Having contacted theUpdateNewsImage(news) technique, the thingnews Having the appropriate picture data, is filled out properly, however theModelState.IsValid real estate is stillfalse bug fixingModelState.Values produces the following error: The NewsImage box must be filled out..


How do I assemble the[Required] (or another technique requiring a picture for each)News object) on theNewsImage property?

1
1
1/31/2011 1:22:41 PM

Accepted Answer

Why not include a[Required] on attributeNewsImage an internal attribute of your validation class? It will then be necessary for aNews each entity instance corresponds to aNewsImage also an entity instance.

When reference (i.e., non-string) type properties are given the RequiredAttribute, it just verifies that the property is not null. Let me support this with theRequiredAttribute.IsValid() method:

public override bool IsValid(object value)
{
    if (value == null)
    {
        return false;
    }
    string str = value as string;
    if (str != null)
    {
        return (str.Trim().Length != 0);
    }
    return true;
}

If the state of your model is incorrect, it signifies that yourNewsImage is void. Perhaps you're overlooking something simple here, and another attribute renders your model state incorrect.

binding file data in ASP.NET MVC

I got it. You seem to believe that every time you make changes to your model, the model state will automatically be verified. Of course, that is not the case. Before performing the action, Asp.net MVC automatically verifies your action parameters for you. Therefore, no matter what you do to your model objects, if your model state is invalid when you are in the body of your action method, it will remain that way. Unless, of course, you manually change the state of the model. When you include the picture in yourNews doesn't alter the model state yet (even though your object becomes valid).

As far as I can see, you struggle with kinds. The default model binder for Asp.net MVC may automatically tie uploaded file streams to models.HttpPostedFileBase variables. YourNewsImage.Image a kind of propertybyte[] Thus, it is not automatically constrained.

The issue is because you're utilizing data model entities as application/view model entities in your web application, thus you can't easily alter that.NewsImage.Image as it's a component of your EF data model.

Writing a distinct view model entity class (don't mix it with EF data model) with the appropriate property types and adding a public function that converts it to data model would probably be the best/easiest approach to get this thing happen.News entity.

namespace WebProject.ViewModels
{
    public class News
    {
        public int Id { get; set; } // not used when creating new entries but used with editing/deleting hens not being required

        [Required]
        public string Text { get; set; }

        [Required]
        public HttpPostedFileBase Image { get; set; }

        public Data.News ToData()
        {
            return new Data.News {
                Id = this.Id,
                Text = this.Text,
                NewsImage = new Data.NewsImage {
                    Id = this.Id,
                    Image = // convert to byte[]
                }
            }
        }
    }
}

As a result, your view model object will be appropriately model bound and verified. The good news is that this adjustment will also result in a simplification of your code. UseToData() when you need to acquire the instance of a data entity from this view model object. Naturally, you could do the opposite as well by offering a constructor that accepts the data model entity object instance and populates the view model's attributes.

I advise placing your view model class alone in the web application project (or any other application model project) since that is where it is utilized if you use a separate database project where you maintain your EF data model.

6
1/31/2011 2:00:48 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow