-1

Ok so my problem is quite simple but i don't see why database is not accepting my form even if i for me set up everything correctly.

I'd like to ask you , why controller does not want to save image to a folder on my project? I have tried with debugging and it says that property urlFotografije is equal to null.

SOLUTION -- So i made mistake during model creating phase as I put required validation in property "urlFotografije" - this can't be required since every time form will report is as null since it value is not passed on.

Controller -

[HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Create([Bind(Include = "AutomobilId,Marka,Model,ZapreminaMotora,Snaga,Gorivo,Karoserija,urlFotografije,Opis,Cena,Kontakt")] Automobil automobil, 
        HttpPostedFileBase file)
    {
        if (file != null)
        {
           ModelState.AddModelError("file", "niste odabrali sliku");
        }

        if (ModelState.IsValid)
        {
            string imageName = System.IO.Path.GetFileName(file.FileName);
            string putanja = Server.MapPath("/Images/"+ imageName);

            file.SaveAs(putanja);
            automobil.urlFotografije = imageName;


            try
            {
                db.Automobili.Add(automobil);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            catch (Exception)
            {
                ViewBag.Greska = "Greska pri cuvanju podataka";
            }
        }

        return View(automobil);
    }

View --

@model WebProdajaAutomobila.Models.Automobil

@{
ViewBag.Title = "Create";
}

<h2>Create</h2>


<form action="/Automobil/Create" method="post" enctype="multipart/form-data">
@Html.AntiForgeryToken()
<div class="form-horizontal">
    <h4>Automobil</h4>
    <hr />

    <div class="form-group">
        <label class="control-label col-md-2" for="Marka">Marka</label>
        <div class="col-md-10">
            <input class="form-control text-box single-line" data-val="true" data-val-length="Max 30 karaktera" data-val-length-max="30" data-val-required="Unesite marku vozila" id="Marka" name="Marka" type="text" value="" />
            <span class="field-validation-valid text-danger" data-valmsg-for="Marka" data-valmsg-replace="true"></span>
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2" for="Model">Model</label>
        <div class="col-md-10">
            <input class="form-control text-box single-line" data-val="true" data-val-length="Max 30 karaktera" data-val-length-max="30" data-val-required="Unesite model vozila" id="Model" name="Model" type="text" value="" />
            <span class="field-validation-valid text-danger" data-valmsg-for="Model" data-valmsg-replace="true"></span>
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2" for="ZapreminaMotora">ZapreminaMotora</label>
        <div class="col-md-10">
            <input class="form-control text-box single-line" data-val="true" data-val-number="The field ZapreminaMotora must be a number." data-val-required="Unesite zapreminu motora" id="ZapreminaMotora" name="ZapreminaMotora" type="text" value="" />
            <span class="field-validation-valid text-danger" data-valmsg-for="ZapreminaMotora" data-valmsg-replace="true"></span>
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2" for="Snaga">Snaga</label>
        <div class="col-md-10">
            <input class="form-control text-box single-line" data-val="true" data-val-number="The field Snaga must be a number." data-val-required="Unesite snagu motora" id="Snaga" name="Snaga" type="number" value="" />
            <span class="field-validation-valid text-danger" data-valmsg-for="Snaga" data-valmsg-replace="true"></span>
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2" for="Gorivo">Gorivo</label>
        <div class="col-md-10">
            <input class="form-control text-box single-line" data-val="true" data-val-length="Max 20 karaktera" data-val-length-max="20" data-val-required="Unesite gorivo vozila" id="Gorivo" name="Gorivo" type="text" value="" />
            <span class="field-validation-valid text-danger" data-valmsg-for="Gorivo" data-valmsg-replace="true"></span>
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2" for="Karoserija">Karoserija</label>
        <div class="col-md-10">
            <input class="form-control text-box single-line" data-val="true" data-val-length="Max 30 karaktera" data-val-length-max="30" data-val-required="Unesite karoseriju vozila" id="Karoserija" name="Karoserija" type="text" value="" />
            <span class="field-validation-valid text-danger" data-valmsg-for="Karoserija" data-valmsg-replace="true"></span>
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2">Odaberi sliku</label>
        <div class="col-md-10">
            <input id="File1" type="file" name="file"/>
        </div> 
    </div>

    <div class="form-group">
        <label class="control-label col-md-2" for="Opis">Opis</label>
        <div class="col-md-10">
            <input class="form-control text-box single-line" data-val="true" data-val-length="Max 100 karaktera" data-val-length-max="100" data-val-required="Unesite opis vozila" id="Opis" name="Opis" type="text" value="" />
            <span class="field-validation-valid text-danger" data-valmsg-for="Opis" data-valmsg-replace="true"></span>
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2" for="Cena">Cena</label>
        <div class="col-md-10">
            <input class="form-control text-box single-line" data-val="true" data-val-number="The field Cena must be a number." data-val-required="Unesite cijenu" id="Cena" name="Cena" type="text" value="" />
            <span class="field-validation-valid text-danger" data-valmsg-for="Cena" data-valmsg-replace="true"></span>
        </div>
    </div>

    <div class="form-group">
        <label class="control-label col-md-2" for="Kontakt">Kontakt</label>
        <div class="col-md-10">
            <input class="form-control text-box single-line" data-val="true" data-val-number="The field Kontakt must be a number." data-val-required="Unesite kontakt" id="Kontakt" name="Kontakt" type="number" value="" />
            <span class="field-validation-valid text-danger" data-valmsg-for="Kontakt" data-valmsg-replace="true"></span>
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>

Blazo
  • 95
  • 1
  • 2
  • 13
  • *"it says that property urlFotografije is equal to null"* - It's not clear to me exactly what problem you're describing. Where specifically is this value equal to `null`? You're setting the value about halfway through the code, is it before or after that where it's `null`? Is the problem that this field is being stored as `null` in the database? Or that the file isn't being saved at all? (The latter doesn't seem to have anything to do with that field.) The question is unclear. – David Feb 06 '19 at 18:56
  • Program goes straight to - return View(automobil); - it enters this method Create, does not pass validation as that property urlFotografije = null and returns view - i want it something like this - https://stackoverflow.com/questions/20825119/how-to-save-image-in-database-and-display-it-into-views-in-mvc-4 – Blazo Feb 06 '19 at 18:58
  • What's the validation rule that's failing? If the model isn't valid then the model isn't valid. You'd either remove the requirement for validation or fix whatever's making it invalid. Is that field marked as required on the model? If it's required, where are you expecting its value to come from? – David Feb 06 '19 at 19:01
  • It is marked as required on the model, i was expecting it to come from the input on cshtml since i set same name as name of argument in method, there i assigned at the end - automobil.urlFotografije = imageName; -- sorry if I format bad these things – Blazo Feb 06 '19 at 19:07
  • *"i was expecting it to come from the input on cshtml"* - Which input? I don't see any input named "urlFotografije" in your view. So I guess it's not clear why you are expecting the view to be sending a value for that field. – David Feb 06 '19 at 19:10
  • Can you check that stackoverflow link i gave you? I got that somewhere I am not correct, but his Index view is something like mine, if you have one minute inspect his Index view and his controller. – Blazo Feb 06 '19 at 19:13
  • Check it for what? His code looks very different than yours. Focus less on making an inventory of differences between his code vs. yours and more on correcting what is wrong in your code. Currently you have a view model which has a required field that you are not providing, so it's failing validation. Either provide the value in your form or make the field not be required. – David Feb 06 '19 at 19:16
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/188016/discussion-between-blazo-and-david). – Blazo Feb 06 '19 at 19:18

1 Answers1

1

According to a lengthy comment thread on the question above, the problem being observed in your debugging has nothing to do with saving a file or writing to a database. According to your debugging, that entire block of code is simply being skipped because this is false:

if (ModelState.IsValid)

This just comes down to the validation rules defined on your model (Automobil) and what values your form is passing to the controller action. According to that comment thread, the field urlFotografije is marked as Required in your model.

But that field is nowwhere to be found in the form in your view. Since the form isn't posting a value for that field, the field has no value. Since it's a required field, the model is invalid and the rest of the code doesn't execute.

You essentially have a few options:

  1. Provide a value for the field. This would mean adding another input to your form with the name urlFotografije and putting a value in that input before posting the form.
  2. Make the field not be required. This would just mean removing the Required validation rule in the model. Then your form wouldn't need to provide a value for that field.
  3. Don't check if the model is valid before executing your code. Perhaps not ideal, but there are cases where it doesn't really matter.
  4. Rearrange your logic so you can manually populate the value before checking the model validation.

Based on your code, it looks like Option 4 is most likely the way to go. You are manually providing a value in that field, but you're doing so after you checked the model state. Reverse that. Possibly something like this:

string imageName = System.IO.Path.GetFileName(file.FileName);
string putanja = Server.MapPath("/Images/"+ imageName);
automobil.urlFotografije = imageName;

if (ModelState.IsValid)
{
    file.SaveAs(putanja);

    try
    {
        db.Automobili.Add(automobil);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    catch (Exception)
    {
        ViewBag.Greska = "Greska pri cuvanju podataka";
    }
}

Note how the calculated values are defined and that property is populated before checking the model validation state. Then, if the model is valid, the rest of the code which actually writes data to the file system and database is then executed.


Side note: Your catch block is ignoring valuable information about any exception which occurs. When you catch the exception, catch it into a variable:

catch (Exception ex)

Then in your catch block you can observe and act upon the information in ex, including logging it or providing a more useful error message.

David
  • 208,112
  • 36
  • 198
  • 279
  • Thank you for your answer - I needed someone to explain me like this since it is my first project for a client i am doing in ASP.NET MVC. 2nd option was the key to this, since removing Required validation from model form anymore does not request it during submitting. Again, thank you for your help! – Blazo Feb 06 '19 at 23:02