Home Null Entry for NonNullable Type in ASP.Net MVC 5 project
Reply: 1

Null Entry for NonNullable Type in ASP.Net MVC 5 project

Unbreakable
1#
Unbreakable Published in 2017-09-10 21:37:20Z

I have a property in Model which needs to be Non Nullable. When submitting a Form if model state isinvalid, I want the user to get redirected to the same page. But whenever ModelState is Invalid I am getting exception as

Exception

The parameters dictionary contains a null entry for parameter 'referralId' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult ReferralConfirmation(Int32)' in 'Bridge.Controllers.ReferrerController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter. Parameter name: parameters

Model:

public class ReferrerInstanceViewModel
    {
        [Key]
        public int Id { get; set; }

        [FileType("pdf|doc|docx|PDF", ErrorMessage = "File type is not valid.")]
        [Required]
        public HttpPostedFileBase ProofDoc { get; set; }

        [Required]
        public int ReferralId { get; set; }

        [Required]
        public int? ReferralStatusId { get; set; }
        public IEnumerable<SelectListItem> ReferralStatuses { get; set; }

    }

Controller Action:

    public ActionResult ReferralConfirmation(int referralId)
    {
        var viewModel = new ReferrerInstanceViewModel
        {
            ReferralId = referralId,
            ReferralStatuses = _context.ReferralStatuses.Select(x => new SelectListItem
            {
                Text = x.ReferralStatusType,
                Value = x.ReferralStatusId.ToString()
            })
        };

        return View(viewModel);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult ReferralConfirmation(ReferrerInstanceViewModel viewModel)
    {
        if (!ModelState.IsValid)
            return RedirectToAction("ReferralConfirmation", viewModel.ReferralId);
       // Some Logic

        return RedirectToAction("ReferrerCenter");
    }

View:

@using (Html.BeginForm("ReferralConfirmation", "Referrer", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.HiddenFor(m=>m.ReferralId)

    <div class="form-horizontal">
        <h4>ReferrerInstanceViewModel</h4>
        <hr />
        @Html.ValidationSummary(false, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.ReferralStatusId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.DropDownListFor(model => model.ReferralStatusId, Model.ReferralStatuses, "Reject Or Refer", new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.ReferralId, "*", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.ProofDoc, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(m => m.ProofDoc, new { type = "file" })
                @Html.ValidationMessageFor(model => model.ProofDoc, "*", new { @class = "text-danger" })
            </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>
}

Points to be noted:

  1. When ModelState is Invalid, I am calling RedirectToAction("ReferralConfirmation", I AM PASSING THE REQUIRED ReferralId VALUE HERE)
  2. When the Model State is Invalid, even the BreakPoint at HTTPGET ReferralConfirmation Action is not getting hit.

I am not able to understand this behavour. What's wrong am I doing.

Kindly note that the Url that's getting generated after ModelState is Invalid is

https://localhost:44328/Referrer/ReferralConfirmation

Shyju
2#
Shyju Reply to 2017-09-10 21:55:41Z

When calling the RedirectToAction with an object, you should pass an anonymous object with a property name matching with the parameter name of your ReferralConfirmation action method

return RedirectToAction("ReferralConfirmation", 
                                   new { referralId = viewModel.ReferralId } );

This will return a 302 response with the location value as /ReferralConfirmation?referralId=100 assuming the value in viewModel.ReferralId is 100

Also when the model state is not valid, there is no point in doing a redirect. You should return to the same view so that user can fix the view and resubmit.

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ReferralConfirmation(ReferrerInstanceViewModel viewModel)
{
    if (ModelState.IsValid)
    {
       //to do : Your code before the redirect goes here

        return RedirectToAction("ReferralConfirmation", 
                                         new { referralId = viewModel.ReferralId });
    }
    //model validation failed. Let's return to same view
    return View(viewModel);
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.317491 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO