Strange Behavior in Razor MVC while using Html.Hel

2019-07-30 09:41发布

问题:

I am using Razor HtmlHelpers. using the code below i tried to print the value of ViewItemDto but it always show 0 for using @Html.TextBoxFor or any @Html...For(x=>..) method.

Does anybody have a idea why this is happening?

Note - The method is returning proper value as i can debug and see the value in debug window on views side.

[DataContract]
[Serializable]
public class ViewItemDto 
{
    [DataMember]        
    public decimal ViewItemId { get; set; }

    [DataMember]        
    public string ItemName { get; set; }
}

From Controller Return 
public ActionResult Index()
    {
        ViewItemDto viewItem = new ViewItemDto();
        viewItem.ItemName = "OldData";
        viewItem.ViewItemId = 10;
        return View(viewItem);
    }

    public PartialViewResult SaveData(ViewItemDto viewItem)
    {
        viewItem.ItemName = "NewData";
        viewItem.ViewItemId = 100;
        return PartialView("ViewUserControl1", viewItem);
    }

On View ViewUserControl1

@model Testing.Models.ViewItemDto
<div id="divSave">
@using (Ajax.BeginForm("SaveData", "Home", new AjaxOptions()
{
   UpdateTargetId = "divSave",
   OnSuccess = "OnSuccess",
   InsertionMode = InsertionMode.Replace
}))
{
    @Html.TextBoxFor(x => x.ViewItemId)//Shows 10
    @Html.TextBox("ID", Model.ViewItemId) //Shows proper value 100
    @Html.TextBoxFor(x => x.ItemName)//Shows oldData value 
    <input type="submit" name="name" value="Submit" />
}

and Index.cshtml

@model Testing.Models.ViewItemDto
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Index</h2>

@Html.Partial("ViewUserControl1", Model);

回答1:

Shouldn't you be:

  return PartialView(viewItem);

instead of:

  return viewItem;


回答2:

By changing the code of your controller to the following it worked here:

public PartialViewResult SaveData(ViewItemDto viewItem)
{
   viewItem.ViewItemId = 100;
   return viewItem;
}

I was unabled to reproduce your problem, since the code provided not even compiled.