简体   繁体   中英

MVC partial view with int model throws exception

I have created a partial view that allows an int to be updated using the jQuery spinner plugin. This is shown in a qtip tooltip.

@model int
    ...
@Html.TextBoxFor(x => x, new { @class = "spinner" })

and the controller action:

[HttpGet]
public PartialViewResult TaskPriority(int id)
{
    var task = Task.Get(id);
    return PartialView("TaskPriority", task.Priority);
}

When I call the action from my page I get:

Value cannot be null or empty. Parameter name: name

The exception is thrown on the TextBoxFor line.

So what am I doing wrong here and why is it wrong? Am I overcomplicating it?

View engine tries to retrieve name for the text box. Generally it is constructed from the name of the property being used as a source for the text box. Note how first parameter of TextBoxFor described on MSDN :

expression

An expression that identifies the object that contains the properties to render.

In this case there is not property, and therefore there is nothing to get name from.

To resolve it you can use Html.TextBox and specify name explicitly:

@Html.TextBox("priority", Model, new { @class = "spinner" })

Well, I would really suspect some problem using a primitive type as model.

You could do

@model Task

@Html.TextBoxFor(x => x.Priority, new{@class="spinner"})

and in your controller

return PartialView("TaskPriority", task);

Solution2 : use a ViewModel , with only one integer property.

Try this,

Model

  public class RegisterModel
    {
        public int ID { get; set; }
}

View

@model RegisterModel

@Html.TextBoxFor(x => x.ID, new { @class = "spinner" })


or
@Html.TextBox("ID",null, new { @class = "spinner" })

Controller

[HttpGet]
public PartialViewResult TaskPriority(int ID)
{
    var task = Task.Get(ID);
    return PartialView("TaskPriority", task );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM