PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, May 18, 2022

[FIXED] Why Does MVC Not Bind when using Partial Views?

 May 18, 2022     asp.net-mvc, c#, partial     No comments   

Issue

Can someone tell me how I can get MVC to bind to a view model within a view model when using partial views?

 public class HomeController : Controller
    {
        //
        // GET: /Home/

        [HttpGet]
        public ActionResult Index()
        {
            AVm a = new AVm();
            BVm b = new BVm();
            a.BVm = b;

            return View(a);
        }

        [HttpPost]
        public ActionResult Index(AVm vm)
        {
            string name = vm.BVm.Name; // will crash BVm == null


            return View(vm);
        }
    }

// Index View

@model MvcApplication4.Models.AVm

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

@using (Html.BeginForm("Index","Home",FormMethod.Post))
{
    <text>Id:</text> @Html.TextBoxFor(x => x.Id)
    @Html.Partial("SharedView", Model.BVm)

    <input type="submit" value="submit" />
}

// SharedView

@model MvcApplication4.Models.BVm

<text>Name:</text> @Html.TextBoxFor(x => x.Name)



 Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 26:         public ActionResult Index(AVm vm)
Line 27:         {
Line 28:             string name = vm.BVm.Name; // will crash BVm == null
Line 29: 
Line 30: 

Solution

The problem is that in your partial the model BVm doesn't know that its a property on a viewmodel AVm. So when you do something like @Html.TextBoxFor(x => x.Name) it will just generate something like

<input type="text" name="Name" id="Name" value="" />

When what you really need is something like

<input type="text" name="BVm.Name" id="Name" value="" />

You could either generate the inputs yourself like suggested here, or you could try something like:

public ActionResult Index(AVm vm, BVm bvm)

Assuming there's no conflicting property names.



Answered By - David Esteves
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing